This is my code below where i created two datas with first pin for example 1111 and another 2222 , where if i use the first pin from the database(ie 1111) it fetches the data from mongodb and returns login successful but if i take another pin(ie 2222) it says invalid pin. May i know what is wrong with the code?
import pymongo
import sys
cluster = pymongo.MongoClient("mongodb://localhost:27017/")
db = cluster['test']
collection = db['test']
login_data = int(input("Enter the pin:"))
result = collection.find({})
for item in result:
if login_data == item['pin']:
print("Login successfully")
break
else:
login_data != item['pin']
print("Invalid pin")
sys.exit(0)
Your loop never has chance to iterate more than once because you either break or sys.exit. Your operation can be simplified by using a filter criteria and a find_one(), no need for a for loop, e.g.
result = collection.find_one({'pin': login_data})
if result is None:
print("Invalid pin")
sys.exit(0)
print("Login successfully")
Related
So i am working on a program that is and I am stuck.
I have a login and signup system that saves new signups in a mysql database.
At the start of the program I take the passwords and names and put them together in a tuple.
Then i put that tuple in a list.
If i wanna login it cant check a tuple in that list.
Here is my code:
Login:
def login():
userKnown = input("Hallo, heeft u al een account? y/n ")
if userKnown == "y":
user = input("username: ")
passw = input("password: ")
userjoin = (user,passw)
if userjoin in bigdata:
print("login succesful")
else:
print("try again")
UploadData:
def uploadData():
print("Bezig met uploaden.")
mycursor.execute("SELECT name, password FROM userData")
data = mycursor.fetchall()
bigdata.append(data)
print("Upload worked. \n")
I hope someone can help me.
A fix to the login system.
I solved it thanks to Georg Richter.
I used the Where function in select and that worked
Here is the code:
def login():
userKnown = input("Hallo, heeft u al een account? y/n ")
if userKnown == "y":
user = input("username: ")
passw = input("password: ")
userB = (user, passw)
query = 'SELECT name, password FROM userData WHERE name =%s'
name = (user,)
mycursor.execute(query, name)
userA = mycursor.fetchone()
print(userA)
if userA == userB:
print("succes")
else:
print("failed")
I think the error is that bigdata does not exist into your login function.
Try this: def login(bigdata) and call the function in this way: login(bigdata)
Try using try block to find the user its easier this way.
try:
pass
#code to search database
except Exception as e:
print(e)
SELECT has a WHERE clause where you can specify user and password to optimize your application.
I have this code
log_in = f'SELECT user_name,fname FROM users;'
cursor = connection.cursor()
cursor.execute(log_in)
result = cursor.fetchall()
cursor.close()
print(type(result))
print(result)
print('bfuqua' in result)
if 'bfuqua' in result:
unique = False
print('That user name already exists. Please try again.')
When I print the type I get <class 'list'> as the return type, [('bfuqua',)] as the data from the result variable. My problem is that it should be entering into the if statement but the return from the third print statement says False. It comes back as True when I put result[0], but I need to be able to scan the whole list for the string. I don't know what is going on.
If there are any other ways I can check to see if the string is in the return from the query, I am more than open to hear it!
Well if you would like to use your code you can iterate over result to achieve what you want:
for i in result:
if 'bfuqua' in i:
unique = False
print('That user name already exists. Please try again.')
But if you want to do it in a way suggested by #iuvbio I'd do it like:
def check_if_user_exists(username):
#by using "with" you dont need to worry about closing the connection
with connection.cursor() as cursor:
log_in = "SELECT user_name, fname FROM users WHERE user_name = %s"
cursor.execute(log_in, (username,))
result = cursor.fetchall()
# If there is no user, the result will be a tuple with 0 length
if len(result) == 0:
print("No user named {}".format(username))
# So here you can create user
else:
print("User {} already exists".format(username))
# Here you can create a notification for a client that the username already exists
check_if_user_exists("bfuqua")
I'm also a beginner so dont treat it like the one and only good solution but it works for me. Hope I was able to help :)
i am trying to validate every input value but stuck here where if user put wrong value then my function stop taking other input & ask him to correct the error.
import re
import os.path
from csv import DictWriter
service ={}
class App:
def __init__(self):
pass
def services(self):
Problem is here
name=input("Enter Name: ")
name_r = re.match('^[a-zA-Z]{3,20}$',name)
if name_r:
print("true")
else:
print("Wrong Value Entered. Please Enter Correct Name")
i wanna use try & except block but exactly don't know how to use in this case.
if i put validated value in except block then rest of the input will also have have their own except block (am confused guide me) also the main problem, is there any short way to do this because if i validate each line like this so it will take so much time.
phone=input("Enter PTCL: ")
email=input("Enter Email: ")
mobile=input("Enter Mobile: ")
address=input("Enter Address: ")
service_type=input("Enter Problem Type: ")
date_time=input("Enter Date & Time: ")
msg=input("Enter Message: ")
Below Code is fine
#getting input values
service['name'] = name_r
service['ptcl'] = phone
service['mobile'] = mobile
service['date_time'] = date_time
service['service_type'] = service_type
service['address'] = address
service['msg'] = msg
service['email'] = email
file_exists = os.path.isfile(r"sevices.csv")
with open(r"sevices.csv",'a',newline='') as for_write:
writing_data = DictWriter(for_write,delimiter=',',fieldnames=["Name","Email","PTCL","Mobile","Service Type","Date & Time","Address","Message"])
if not file_exists:
writing_data.writeheader()
writing_data.writerow({
'Name': service['name'],
'Email':service['email'],
'PTCL':service['ptcl'],
'Mobile':service['mobile'],
'Service Type':service['service_type'],
'Date & Time':service['date_time'],
'Address':service['address'],
'Message':service['msg']
})
o1= App()
o1.services()
The easiest way to accomplish what you want is to create a while loop that exits on an accepted input.
while True:
name=input("Enter Name: ")
name_r = re.match('^[a-zA-Z]{3,20}$',name)
if name_r:
break
else:
print("Wrong Value Entered. Please Enter Correct Name")
I've been trying to create a really simple login screen on python for fun. Somewhere else in the program I have it save the entered username and password as a str (in dict format) on an external file. I can get it to check if the key-username- is correct but i cant find a way to make it check if the password entered is the password linked with the key -the value- I might of worded this weirdly but does any one have any idea how?
def login():
clear()
gap()
loginu = input("ENTER YOUR USERNAME:")
gap()
file = open("usernamesf.txt","r")
usernra = file.read()
usernr = usernra.replace("'","")
usernw = '"{' + usernr + '}"'
print (usernw)
usernwl = ast.literal_eval(usernw)
print (usernwl)
if loginu in usernwl:
gap()
loginp = input("ENTER YOUR PASSWORD:")
loginpc = usernw[loginu]
if loginp in loginpc:
print ("yay")
else:
gap()
print ("NO USERNAME FOUND...")
time.sleep(0.5)
gap()
signu = input("Would you like to sign up?")
if signu in ['yes','y','Y','Yes',' yes',' Yes',' y',' Y']:
sign()
else:
menu()
I would first recommend that you use the json library to parse your file - it is able to convert python dictionaries to string and vice versa, which is really useful.
To convert dict to str:
json.dumps(dictionary)
To convert str to dict: json.loads(string)
With this, to read the dictionary from the file, it is simply:
import json
with open("usernamesf.txt") as f:
user_dictionary = json.loads(f.read())
if loginu in user_dictionary:
password = input("ENTER YOUR PASSWORD")
if user_dictionary[username] == password:
# success
Notice how i used the with statement here for the file - this ensures that the file is properly closed by python after you are done with it - that is, after you exit the with block. You can read more about this in the official python documentation on file I/O here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
I've recently started learning Python API's and I've run into a problem while trying to access the HaveIBeenPwned API. I can get it to print the JSON data so I think it's a formatting problem? All other solutions seem to force me to rewrite my entire code only to find it doesn't work anyway or is incompatible.
#This program aims to provide 4 search functions by which users can test if their data is at risk.
import urllib.request as url
import json
import ast
def UsernameSearch():
print("Username search selected!")
def PasswordSearch():
print("Password search selected!")
def EmailSearch():
Username = input("Please enter the Email that's going to be searched \n: ")
def DataGetCurrent(Username):
SearchURL = "https://haveibeenpwned.com/api/v2/breachedaccount/{}".format(Username)
request = url.urlopen(url.Request(SearchURL, headers={'User-Agent' : "Mozilla/5.0"}))
data = request.read()
data = data.decode("utf-8")
json_data = json.loads(data)
return json_data[0]
Data = DataGetCurrent(Username)
a = ("Your Email address has been involved in [number] breaches: \nBreach \nTitle: {}\nWebsite: {}\nDate: {}\nInformation: {}\nLeaked Data: {}".format(Data['Title'],Data['Domain'],Data['BreachDate'],Data['Description'],Data['DataClasses']))
print(a)
def SiteSearch():
print("Website search selected!")
def loop():
try:
answer = input("There are currently 5 options: \n(1)Username search \n(2)Password search \n(3)Email search \n(4)Website search \n(5)Exit \n \n:")
if answer.upper() == "1":
UsernameSearch()
elif answer.upper() == "2":
PasswordSearch()
elif answer.upper() == "3":
EmailSearch()
elif answer.upper() == "4":
SiteSearch()
else:
print("\nThis is invalid, sorry. Please try again!\n")
loop()
except KeyboardInterrupt:
print("\nYou don't need to exit the program this way, there's an exit option; just type \"exit\"!\n")
loop()
loop()
The error it throws is:
TypeError: string indices must be integers
Edit:
Updated now and it does call some information however it only calls the first dictionary entry whereas I need it to call as many as there are (and preferably have a count variable sometimes).
I'm also having trouble selecting the "DataClasses" entry and printing the individual entities within.
All help is appreciated, thanks.
To convert a json string to dictionary, use json module (standard library):
import json
data_str = '{"index" : 5}'
json_dict = json.loads(data_str)
In your example:
import json
# ...
def DataGetCurrent(Username):
SearchURL = "https://haveibeenpwned.com/api/v2/breachedaccount/{}".format(Username)
request = url.urlopen(url.Request(SearchURL, headers={'User-Agent' : "Mozilla/5.0"}))
data = request.read()
data = data.decode("utf-8")
return json.loads(data)
EDIT
Apparently HaveIBeenPwned returns a list of dictionaries. Therefore, to get the results, you need to get the dictionary in the 0th index of the list:
def DataGetCurrent(Username):
SearchURL = "https://haveibeenpwned.com/api/v2/breachedaccount/{}".format(Username)
request = url.urlopen(url.Request(SearchURL, headers={'User-Agent' : "Mozilla/5.0"}))
data = request.read()
data = data.decode("utf-8")
json_list = json.loads(data)
return json_list[0]
EDIT 2
0th element of the list is only one of the results. To process all the results, the list itself should be returned and used accordingly.