import sqlite3
conn = sqlite3.connect('LeVinEmployee.db')
profile = input("Are you a user? y/n: ")
if profile == 'y':
login = input("Enter login name: ")
#passw = input("Enter password: ")
c = conn.cursor()
c.execute("SELECT * FROM Employee WHERE Email = '" + login + "'")
result = c.fetchone()
if result[0] == 1:
print(c.fetchall())
else:
print("not")
else:
print("You are not a user")
What I am trying to do here is pretty simple. I am trying to create user login function. If user type 'y', program will simply ask to put login email. If user type correct email from database, print that customer information. if wrong, print 'not'. I am not sure what is wrong with my code. Can someone help me please?
As I understand, email is an unique field. And your query could return one record or nothing (None). Try
result = c.fetchone()
if result: # result could be None or tuple (record)
print(result)
else:
print("not")
Also, such method of parameter pass is incorrect (insecure)
c.execute("SELECT * FROM Employee WHERE Email = '" + login + "'")
use
c.execute("SELECT * FROM Employee WHERE Email=?", login)
more info here.
Related
Hey I am trying to create a system using text files where a user can sign up and log in. All the data will be stored in plain text in a text file called User_Data.txt. My code works but I would like to know if there is anything I missed or If I could improve it in any way. Sorry for the Bad code Formatting in advance.
def choices():
print("Please choose what you would like to do.")
choice = int(input("For Sigining Up Type 1 and For Signing in Type 2: "))
if choice == 1:
return getdetails()
elif choice == 2:
return checkdetails()
else:
raise TypeError
def getdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
if name in info:
return "Name Unavailable. Please Try Again"
f.close()
f = open("User_Data.txt",'w')
info = info + " " +name + " " + password
f.write(info)
def checkdetails():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
f = open("User_Data.txt",'r')
info = f.read()
info = info.split()
if name in info:
index = info.index(name) + 1
usr_password = info[index]
if usr_password == password:
return "Welcome Back, " + name
else:
return "Password entered is wrong"
else:
return "Name not found. Please Sign Up."
print(choices())
There is a lot of improvements You could do.
First of all, split functionality to smaller function.
PASSWORD_FNAME = "User_Data.txt"
def get_existing_users():
with open("r", PASSWORD_FNAME ) as fp:
for line in fp.readlines():
# This expects each line of a file to be (name, pass) seperated by whitespace
username, password = line.split()
yield username, password
def is_authorized(username, password):
return any((user == (username, password) for user in get_existing_users())
def user_exists(username):
return any((usr_name == username) for usr_name, _ in get_existing_users())
# above is equivalent of:
#
# for usr_name, _ in get_existing_users():
# if usr_name == username:
# return True
# return False
def ask_user_credentials():
print("Please Provide")
name = str(input("Name: "))
password = str(input("Password: "))
return name, password
def checkdetails():
name, password = ask_user_credentials()
if is_authorized(name, password):
return "Welcome Back, " + name
if user_exists(name):
return "Password entered is wrong"
return "Name not found. Please Sign Up."
def getdetails():
name, password = ask_user_credentials()
if not user_exists(name):
return "Name Unavailable. Please Try Again"
# Not sure tho what would You like to do here
It's always good to remember to always close your file if you read it.
So if you do something like:
f = open("r", "file.txt") remember to always call f.close() later.
If you use context manager and do it like:
with open("r", "file.txt") as fp:
print(fp.read())
it will automatically close the file for you at the end.
Firstly, fix the spelling error at int(input("For Sigining Up Type 1") Other than that I would add some kind of purpose, for example storing secret numbers or something.
For example you can extend your script with a simple password recovery system.
I think it could be useful to learn...
You can implement a sort of a simple hashing system in order to avoid saving the password as plain text.
If you want to add a GUI, please consider using Tkinter.
https://docs.python.org/3/library/tkinter.html
Let we know.
Good Luck and Keep Coding with <3
I'm doing a code where the program ask for personal informations of someone, then he reads those infomations and send to the database. So I have the option to register and to consult. I don't know if the program is with more problems because I need to fix it first.
When I try to register the person It's give me the error "Is not possible to register." and I can't find why.
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
def criardb():
c.execute('CREATE TABLE IF NOT EXISTS pessoas(id INTEGER PRIMARY KEY
AUTOINCREMENT,nome VARCHAR, idade INT, tel VARCHAR, pais VARCHAR)')
conn.commit()
def insertdata(nome,idade,tel,pais):
c.execute = ('INSERT INTO pessoas VALUES (?,?,?,?)',
(nome,idade,tel,pais))
conn.commit()
def consultdata():
sql = c.execute('SELECT * FROM pessoas')
for row in sql:
print("Nome: {}".format(row[0]))
def consultdataind(esc):
sql = c.execute('SELECT * FROM pessoas WHERE id = ?')
for row in sql(sql,(esc)):
print("Nome: {} Idade: {} Telefone: {} País:
{}".format(row[0],int(row[1]),row[2],row[3]))
try:
print("Creating database...")
criardb()
except:
print("ERRO: It was not possible to create the database.")
else:
print("Database successfully created.")
while True:
print("Welcome to the register system, choose a option:")
op = int(input("| 1 - Register | 2 - Consult | 3 - Exit | "))
if op == 1:
n = input("Nome: ")
i = int(input("Idade: "))
t = input("Telefone: ")
p = input("País: ")
try:
insertdata(n,i,t,p)
except:
print("ERRO: It's not possible to register")
else:
print("Successfully registered.")
elif op == 2:
print("List of registered users:")
try:
consultdata()
except:
print("It was not possible to load the list.")
print("Write the person ID to individual consult.")
esc = int(input(">> "))
consultdataind(esc)
elif op == 3:
break
else:
print("Invalid command.")
I need to send all the information to the database and return the consult, first it will show all the registered person then the user can write the respective ID of someone in the list and it will show all the details about this person
Replace your insertdata with this and everything should work fine.
def insertdata(nome,idade,tel,pais):
c.execute('INSERT INTO pessoas (nome,idade,tel,pais) VALUES (?,?,?,?)', [nome,idade,tel,pais])
conn.commit()
You need to call the execute method of the cursor here.
And on the side note, never use except directly without specifying an exception. It hides the simplest of error messages which will make your code very hard to debug. As of now it was AttributeError that was causing this problem as you were trying to assign value to Cursor which is ReadOnly
The issue I am having here is that whenever I try to input data into my Username entry box (self.KUEntry.get()) and run the input from that box within my query, it returns none and throws the error listed in the question.
The function is supposed to check the stored salt and hash of a registered user and compare it with the password that they are typing into the entry box.
def login_verification(self):
username = self.KUEntry.get()
print username
cursor1.execute = ("SELECT salt FROM User WHERE username = (%s)", username)
salty = cursor1.fetchone() [0]
print salty
cursor2.execute = ("SELECT PashHash FROM User WHERE username = %s", (username))
hashy = cursor2.fetchone() [0]
print hashy
test = hashlib.sha512(username + salty).hexdigest
print test
if test == hashy:
self.mainscreen
else:
print "incorrect password"
Putting my code like this fixes the traceback error, but it does not return what is expected. Instead of my cursor1.fetchone and cursor2.fetchone methods returning the result of the query they return "none".
def login_verification(self):
username = self.KUEntry.get()
print username
cursor1.execute = ("SELECT salt FROM User WHERE username = %s", str(username))
salty = str(cursor1.fetchone())
print salty
cursor2.execute = ("SELECT PashHash FROM User WHERE username = %s", str(username))
hashy = str(cursor2.fetchone())
print hashy
test = hashlib.sha512(username + str(salty)).hexdigest
print test
if test == hashy:
self.mainscreen
else:
print "incorrect password"
I am having issues with the current program that I am trying to write. I don't understand why it keeps saying this or why.
Also can this code be extended to cover IP logging and making sure multiple users can be logged in on the same IP in theory?
Here is the code:
import hashlib
import time
#cPickle is faster then pickle but not available in all python releases
#thats why i used a try/accept there
try: import cPickle as cp
#load the database if it exist, if not it create one
try:
f =(r"C:\Users\Owner\Desktop\python\database.data")
data = cp.load(f)
except IOError:
data = {}
#A simple function made to make data dumping easy
def easyDump(data_):
f = file(r"C:\Users\Owner\Desktop\python\database.data", "w")
cp.dump(data_, f)
f.close()
#Get's the date (We'll use this as the custom salt)
def getData():
return str(time.strftime("%d-%m-%Y"))
#A function which accepts two parameters, password and date.
#The date is the custom salt. It returns the sha512 hash excetpyion
def salt(password, date):
salted = hasglib.sha512(password + str(data)).hexdigest()
retun str(salted)
menu = """"
1.Login
2.Register
3.Exit
"""
while True:
print menu
choice = int(raw_input("Your choice please: "))
if choice ==1:
username = raw_input("Enter your username please: ")
password = raw.input("Enter your authentication code please: ")
#if the username is found on the database
if data.has_key(username):
#date is equal to our secured stored data
date = date[username][1]
#check of the given password + date is equal to what is stored on the database
#password
if salt(password, date) == date[username][0]:
print"Welcome %s!" % username
else:
print "Incorrect password"
else:
print "user %s not found, please register!" % username
elif choice == 2:
username = raw_input("Please enter yout username: !")
password = raw_input("Please enter your password: !")
#if username exists in the system already then the name is taken
if data.has_key(username):
print "user %s already registered, please put in another % username
else:
#in order words data = {username: hash, date}
data[username] = [salt(password, getData()), get Data()]
easyDump(data)
print "user %s successfully registereed!" %username
elif choice == 3:
print "goodbye!"
break
else:
print "invaid input or commands"
This code:
try: import cPickle as cp
is not followed by an except ... hence the syntax error
Your code contains many indenting, syntax errors and spelling mistakes. The following fixes these to allow it to at least run:
import hashlib
import time
#cPickle is faster then pickle but not available in all Python releases
#That is why I used a try/accept there
try:
import cPickle as cp
except:
import pickle as cp
#load the database if it exist, if not it create one
try:
f = open(r"C:\Users\Owner\Desktop\python\database.data")
data = cp.load(f)
except IOError:
data = {}
#A simple function made to make data dumping easy
def easyDump(data_):
f = file(r"C:\Users\Owner\Desktop\python\database.data", "w")
cp.dump(data_, f)
f.close()
#Get's the date (We'll use this as the custom salt)
def getData():
return str(time.strftime("%d-%m-%Y"))
#A function which accepts two parameters, password and date.
#The date is the custom salt. It returns the sha512 hash exception
def salt(password, date):
salted = hasglib.sha512(password + str(data)).hexdigest()
return str(salted)
menu = """"
1.Login
2.Register
3.Exit
"""
while True:
print menu
choice = int(raw_input("Your choice please: "))
if choice == 1:
username = raw_input("Enter your username please: ")
password = raw.input("Enter your authentication code please: ")
#if the username is found on the database
if data.has_key(username):
#date is equal to our secured stored data
date = date[username][1]
#check of the given password + date is equal to what is stored on the database
#password
if salt(password, date) == date[username][0]:
print"Welcome %s!" % username
else:
print "Incorrect password"
else:
print "user %s not found, please register!" % username
elif choice == 2:
username = raw_input("Please enter yout username: !")
password = raw_input("Please enter your password: !")
#if username exists in the system already then the name is taken
if data.has_key(username):
print "user %s already registered, please put in another" % username
else:
#in order words data = {username: hash, date}
data[username] = [salt(password, getData()), getData()]
easyDump(data)
print "user %s successfully registered!" % username
elif choice == 3:
print "goodbye!"
break
else:
print "invalid input or commands"
Indenting in Python is very important, getting it wrong can completely change the meaning of the code.
import sqlite3
conn = sqlite3.connect('/Users/macbook/Desktop/lool.db')
c = conn.cursor()
invalid_input = True
def startinglogin(self):
loginmessage = input("To register to the Quizzer, type in 'Register'. To login, type in 'Login'.\n")
while loginmessage != "Login" and loginmessage != "Register":
loginmessage = input("To register to the Quizzer, type in 'Register'. To login, type in 'Login'.\n")
self.loginmessage = loginmessage
studentusername = ' '
studentpassword = ' '
def nameandpass():
global studentusername
studentusername = input('Enter username: ')
global studentpassword
studentpassword = input('Enter password: ')
def start():
def passlength():
while len(studentpassword) < 4 or len(studentpassword) > 16:
print ("ERROR. Your password must be longer than 4 characters and shorter than 16 characters.")
studentpassword = input('Enter password: ')
def usernamechecker():
c.execute("SELECT username FROM studenttest WHERE username=(?)", (studentusername, ))
if c.fetchone() == None:
global usernamecheck
usernamecheck = ' '
else:
c.execute("SELECT username FROM studenttest WHERE username=(?)", (studentusername, ))
usernamecheck = ' '.join(map(str, (c.fetchone())))
def passwordchecker():
c.execute("SELECT password FROM studenttest WHERE password=(?)", (studentpassword, ))
if c.fetchone() == None:
global passcheck
passcheck = ' '
else:
c.execute("SELECT password FROM studenttest WHERE password=(?)", (studentpassword, ))
passcheck = ' '.join(map(str, (c.fetchone())))
def create_db():
c.execute("DROP TABLE IF EXISTS studenttest")
c.execute("CREATE TABLE studenttest (id INTEGER PRIMARY KEY, username TEXT, password TEXT)")
conn.commit()
def loginform():
while usernamecheck != studentusername or passcheck != studentpassword:
print ("Your login info is wrong.")
nameandpass()
usernamechecker()
passwordchecker()
if usernamecheck == studentusername and passcheck == studentpassword:
print ("Access granted!")
global invalid_input
invalid_input = False
else:
print("Access denied!")
def registerform():
while studentusername == useravailable:
print ("That username is already taken!")
global studentusername
studentusername = input("Enter username: ")
if studentusername != useravailable:
c.execute("INSERT INTO studenttest VALUES (NULL,?,?);", (studentusername, studentpassword))
global invalid_input
invalid_input = False
conn.commit()
def sameusername():
c.execute("SELECT username FROM studenttest")
global useravailable
useravailable = ' '.join(map(str, (c.fetchone())))
if startinglogin.loginmessage == "Register":
sameusername()
registerform()
elif startinglogin.loginmessage == "Login":
usernamechecker()
passwordchecker()
loginform()
conn.commit()
while invalid_input:
startinglogin(startinglogin)
nameandpass()
start()
if invalid_input == False:
c.close()
I have no idea why my code is locking the database, can someone help out with that? The error message that is displayed in the shell is:
Traceback (most recent call last):
File "/Users/macbook/Documents/hey draft2.py", line 85, in <module>
start()
File "/Users/macbook/Documents/hey draft2.py", line 75, in start
registerform()
File "/Users/macbook/Documents/hey draft2.py", line 65, in registerform
c.execute("INSERT INTO studenttest VALUES (NULL,?,?);", (studentusername, studentpassword))
sqlite3.OperationalError: database is locked
If this is a noob mistake, I'm really sorry for wasting time. :/
EDIT: Forgot to call passlength() in the code, don't mind that. Adding or taking it out had no effect.
Would you happen to be using a visual tool for sqlite (e.g. sqlitebrowser) while running your code? If you have unwritten changes in the visual tool it might throw errors if you try to run your python code. The fix is to write the changes, then try the code again.
EDIT: This question has an answer that recommends this old sqlite documentation, that might help too.