python-mysql fetchone() type mismatch? - mysql

I have this piece of code that should return the value of the password from the db and match it with the password entered. I appended the characters on this line to match the formatting of the result that it printed.
appended_y= "(u'" + y + "'y,)"
it even though the two print out the same value the if statement rejects it and always falls to else, Can anyone point me down the right path?
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
appended_y= "(u'" + y + "'y,)"
z = "SELECT password FROM members WHERE userid = %s"
self.cursor.execute(z,(x,))
pw=(self.cursor.fetchone())
if appended_y == pw:
self.member_menu()
else:
print "Incorrect name or password. Aborting connection"

Look into the type of pw. It may be a string inside a list or tuple.

Related

I've stumped myself on my login project and suggestions with the order of my code! it is a login project

So I have the code written I think and it works but I am not sure how to order it properly so for example in my menu function when they enter 2 to end the program it will end completely as after I call this function I need to call the others but at the moment it while just run the next part of the code
print("----------------------Welcome User----------------------\n\n")
# this function is used for apperance in the program
def linebreak():
print("---------------------------------------------------------")
# Menu for user to choose what they would like to do
# this functuon gives the user a choice from the menu above if they want to log in it will break out of
# the loop and go onto the next block of code below
def menu():
while True:
print("-----------------------Main Menu------------------------\n")
print("To login enter 1:")
print("To end the program enter 2:")
print("")
try:
sUserSelection = int(input("What would you like to do? \n"))
# make a conditional statement to see if the user wants to start the login program or exit
if sUserSelection == 1:
break
elif sUserSelection == 2:
print("Ending program, Goodbye!")
break
except:
print("ERROR! Invalid choice please choose from the menu to continue or exit the program.\n")
menu()
menu()
# This is a function that will return two print statements one to tell the user that their login was successful
# And it will then print greet with that users inputted name
def welcome_user():
print("Login successful. ")
print("Welcome ")
# Create a function for the admin login
sAdmin = "admin"
sAdminPassWord = "aDmin002"
def admin_login():
print("Please login to the administrator account to create your new personal account: \n")
while True:
sUserInput = input("Please enter admin username: \n")
sUserInput = sUserInput.lower()
if sUserInput == sAdmin:
break
else:
print("Wrong username please try again! \n")
while True:
sPassInput = input("Please enter admin password: \n")
if sPassInput == sAdminPassWord:
print("Login Successful")
break
else:
print("Wrong password please try again! \n")
# this function allows the user to create a new account starting with the username and then
# it asks for the creation of a password
def new_account():
print("\nPlease create a new account.\n")
while True:
global sNewUser1
sNewUser1 = input("\nPlease enter a new username.\n"
"It should be at least 5 characters long\n"
"and not contain spaces or special characters: \n\n")
if len(sNewUser1) < 5:
print("Your username is too short. Please try again: ")
elif sNewUser1.count(" ") > 0:
print("Your username contains spaces. Please try again: ")
elif sNewUser1.isalnum() is False:
print("Your username contains a special character. "
"Please try again: ")
else:
# call another function
break
while True:
global sNewPass1
sNewPass1 = input("\n\nPlease enter a new password.\n"
"It should be at least 6 characters long\n"
"with at least one uppercase letter,\n"
"one lowercase letter, one special character"
"and one number: \n\n")
if len(sNewPass1) < 6:
print("\nYour password is too short. Please try again: ")
elif any(lower.islower() for lower in sNewPass1) is False:
print("\nYour password does not contain lowercase letters. "
"Please try again: ")
elif any(upper.isupper() for upper in sNewPass1) is False:
print("\nYour password does not contain uppercase letters. "
"Please try again: ")
elif any(digit.isdigit() for digit in sNewPass1) is False:
print("\nYour password does not contain a number. "
"Please try again: ")
elif any(not char.isalnum() for char in sNewPass1) is False:
print("\nYour password does not contain a special character. "
"Please try again: ")
elif sNewPass1.replace(" ", "") != sNewPass1:
print("\nYour password contains whitespaces. "
"Please try again: ")
else:
# call another function
break
def name_selection():
print("Account created sucessfully!")
global sName1
sName1 = input("Please enter your name:\n")
def user_login():
while True:
sUserLogin = input("Please enter your username:\n")
if sUserLogin == sNewUser1:
break
else:
print("Wrong username please try again:\n")
while True:
sUserPass = input("Please enter your password:\n")
if sUserPass == sNewPass1:
print("\nWelcome: ", sName1)
break
# # calls the menu function
menu()
# # calls the admin login function
admin_login()
# calls the function to create a new account
new_account()
# calls the name creation function after an account has been made
name_selection()
# calls the function to allow the user to login using there credentials
user_login()

unable to read hash from json file

This is part of my code for creating and logging into accounts in my game, I have cut out the acquisition of the username and password from the user and have just kept the password hashing and file read/writing
##CREATE ACCOUNT##
#Encrypt password
newPswdEnc = hashlib.sha512()
newPswd = bytes(newPswd, "ascii")
newPswdEnc.update(newPswd)
newPswdEnc = str(newPswdEnc.digest()).replace("\\", ".")
#Assemble and place in file
newLogin = {"Username":newUsnm,"Pswd":newPswdEnc,"Highscore":0}
with open("Users.json", "r+") as file:
data = json.load(file)
##DOES SOME EXTRA VALIDATION TO PREVENT DUPLICATE USERNAMES##
data["Logins"].append(newLogin)
with open("Users.json", "w+") as file:
json.dump(data. file, indent = 5)
##LOGIN##
#Encrypt password
pswdEnc = hashlib.sha512()
pswd = bytes(pswd, "ascii")
pswdEnc.update(pswd)
pswdEnc = str(pswdEnc.digest()).replace("\\", ".")
#CHECK USERNAME AND PASSWORD
with open("Users.json", "r") as file:
data = json.load(file)
for i in range(0, len(data["Logins"])):
if data["Logins"][i]["Username"] == usnm and data["Logins"][i]["Pswd"] == pswd:
loggedIn = True
##Logins.json##
{
"Logins": [
{
"Username": "ADMIN",
"Pswd": b'#.x8b.x90.xe6.xe28-.xda.xfa.xdc5&k/.xa9.xa3q.xfb9b.xb6u.xcc.xab.x1bU82.x1fF.x90p.xd0.xf3v/).xb2.x1a.xc7.xadw..xb6.xbd).x9d.t.xf8.xe7]8.xed.x8bpg.x96]]_&.xeb.xc3.xf5',
"Highscore": 0
}
],
}
When attempting to sign in with the correct password I get this error:
Expecting value: line 5 column 24 (char 90)
which appears to be the b character at the start of the hash
Problem with reading was solved by removing my filter for backslashes however I am now experiencing issues with the password comparison as whilst in another program I have put both hashes in variables and validated them. This program is refusing to do so.

Python 2.7 trying to iterate file with usernames and passwords, unable to get data properly

I am using Python 2.7 and I have a text file exactly in this format starting like this:
Username: JohnDoe
Password: JohnsPass
------------------------
Username: Bob
Password: BobsPass
------------------------
It starts the same way you see above and ends the same way as you see.
I have tried the following to get the data in either a dictionary/list so I can import it into mysql.
thefile = open("theaccounts.txt","r")
myAcctList=[]
for line in thefile:
myAcctList.append(line)
thefile.close()
Which shows me:
['Username: JohnDoe\n',
'Password: JohnsPass\n',
'------------------------\n',
'Username: Bob\n',
'Password: BobsPass\n',
'------------------------\n']
I have been trying to get the username/password like so:
for userinfo in myAcctList:
if userinfo.startswith('-------------'):
pass
else:
print userinfo
It shows me:
Username: JohnDoe
Password: JohnsPass
Username: Bob
Password: BobsPass
How can I get this to be on one line or a dictionary even so I can import these into mysql DB? I have tried various things but, they all either error out or it doubles the print out showing the username twice and the password from the previous username as the password.
Is there some way I can do:
print "Username is: %s and password is: %s" % (usernameis,passwordis)
As I would like to set the variable to place into the mysql record in one go, instead of matching the username and then inserting the password.
Please provide suggestions or solutions I have been trying to figure this out and really haven't been able to get it right. Thanks for all input it is greatly appreciated!
Update:
I modified what you showed me and came up with this:
cur_user={}
countlogins=0
for userinfo in myAcctList:
if userinfo.startswith('------------------------'):
pass
else:
forusername=userinfo.split(':')
print "I see index 0 as: %s" % forusername[0]
print "I see index 1 as: %s" % forusername[1]
cur_user[forusername[0]] = forusername[1].strip()
print cur_user
time.sleep(3) #just so I could see the top of the list
This is closer but, it still does some weird doubling up showing the username twice and showing the password for the previous line then the password it should be. It also only shows me the username when it hits the first line (I am guessing because it has not iterated to the 2nd line yet).
Print out is like so:
I see index 0 as: Username
I see index 1 as: JohnDoe
{'Username': 'JohnDoe'}
I see index 0 as: Password
I see index 1 as: JohnPass
{'Username': 'JohnDoe', 'Password': 'JohnPass'}
I see index 0 as: Username
I see index 1 as: BobTheUser
{'Username': 'BobTheUser', 'Password': 'JohnPass'}
I see index 0 as: Password
I see index 1 as: BobsPass
{'Username': 'BobTheUser', 'Password': 'BobsPass'}
I see index 0 as: Username
I see index 1 as: ThisOtherUser
{'Username': 'ThisOtherUser', 'Password': 'BobsPass'}
I counted 5 logins
I see index 0 as: Password
I see index 1 as: ThisOtherUserPass
{'Username': 'ThisOtherUser', 'Password': 'ThisOtherUserPass'}
I see index 0 as: Username
I see index 1 as: YetOneMore
I cannot figure out why it's doubling up like that or why it takes it the 2nd go round to get the info right. This will prevent (if I'm not mistaken) proper insertion into mysql db. I would like to get it just telling me once what I need to know so that I can know it will insert the proper info.
Thanks for your time and assistance!
2nd Update:
I also tried:
theFile = open("theaccounts.txt","r")
users = []
cur_user = {}
for line in theFile:
if line.startswith('------'):
users.append(cur_user)
cur_user = {}
else:
fields = ':'.split(line)
cur_user[fields[0]] = fields[1].strip()
theFile.close()
Which gives me an error:
---> 10 cur_user[fields[0]] = fields[1].strip()
11 theFile.close()
IndexError: list index out of range
So I then tried:
theFile = open("theaccounts.txt","r")
users = []
cur_user = {}
for line in theFile:
if line.startswith('------'):
users.append(cur_user)
cur_user = {}
else:
fields = ':'.split(line)
try:
cur_user[fields[0]] = fields[1].strip()
print cur_user
except:
pass
theFile.close()
Which only gave me:
[{},
{},
{},
{},
{},
{},
{},
{}]
Please help me get this sorted it's really not making sense to me why it's so hard.
3rd Update:
Ok got it figured out! Here is the final result for anyone else who might be needing to do this or gets in trouble:
countlogins=0
theFile = open("theaccounts.txt","r")
myAcctList=[]
cur_user={}
for line in theFile:
if line.startswith('------'):
countlogins=countlogins+1
print cur_user
myAcctList.append(line)
cur_user={}
else:
forusername=line.split(':')
cur_user[forusername[0]] = forusername[1].strip()
theFile.close()
print "I counted %s logins" % countlogins
I did the extra count at the end to verify it matched with what I was told.
Thanks for your help!
Split the line using : as the delimiter. Then use the first part as the key in a dictionary, and the second part as the value. When you get to the ---- line, add the dictionary to your list.
users = []
cur_user = {}
for line in theFile:
if line.startswith('------'):
users.append(cur_user)
cur_user = {}
else:
fields = line.split(':')
cur_user[fields[0]] = fields[1].strip()
In your first update, the doubling up is happening because you're using the same cur_user dictionary for everything. So when you read the second username, you're just overwriting the username of that dictionary, not starting a new one. That's why my answer reassigns cur_user = {} after it adds the current user to the users list.
It takes two steps to get both the username and password into the dictionary, because when you read the first line of the file you haven't yet read the first password. Since you're printing the dictionary after each line, you see this partial result after the first line. You shouldn't try to add to the database until you get to the ----- separator line, that's how you know you have both fields.

Creating a Caesar Cipher Program in Python 3.4, but function doesn't work

Currently, I am creating a Caesar Cipher but it is not working correctly, can anyone help at all? The code will be below. At the moment, if the program is run first time (as in, no functions have to be re run) it works perfectly, but when the getKey() function is re run, it returns an error. After the code, the error is shown:
def runProgram():
def choice():
userChoice = input("Do you wish to Encrypt of Decrypt? Enter E or D: ").lower()
if userChoice == "e":
return userChoice
elif userChoice == "d":
return userChoice
else:
print("Invalid Response. Please try again.")
choice()
def getMessage():
userMessage = input("Enter your message: ")
return userMessage
def getKey():
try:
userKey = int(input("Enter a key number (1-26): "))
except:
print("Invalid Option. Please try again.")
getKey()
else:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
else:
return userKey
def getTranslated(userChoice, message, key):
translated = ""
if userChoice == "e":
for character in message:
num = ord(character)
num += key
translated += chr(num)
savedFile = open('Encrypted.txt', 'w')
savedFile.write(translated)
savedFile.close()
return translated
else:
for character in message:
num = ord(character)
num -= key
translated += chr(num)
return translated
userChoice = choice() #Runs function for encrypt/decrypt selection. Saves choice made.
message = getMessage() #Run function for user to enter message. Saves message.
key = getKey() #Runs function for user to select key. Saves key choice.
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
print("\nTranslation complete: " + translatedMessage)
runProgram()
I have tried to create it error proof during the getKey() function with the try, except and else commands. It will 'Try' to see that the input is an int or not, if it is, it goes to else, but if it isn't an int, then it will rerun the function. If the function is rerun, and an int is entered, this error is given:
This is an example of it working:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): 5
Translation complete: Mjqqt
This is an example when the getKey() function must be re run due to an int not being entered:
Do you wish to Encrypt of Decrypt? Enter E or D: E
Enter your message: Hello
Enter a key number (1-26): H
Invalid Option. Please try again.
Enter a key number (1-26): 5
Traceback (most recent call last):
File "C:\Python34\Encryptor2.py", line 54, in
runProgram()
File "C:\Python34\Encryptor2.py", line 52, in runProgram
translatedMessage = getTranslated(userChoice, message, key) #Runs function to translate message, using the choice, message and key variables)
File "C:\Python34\Encryptor2.py", line 35, in getTranslated
num += key
TypeError: unsupported operand type(s) for +=: 'int' and 'NoneType'
As you can see, it re runs the function as I want it too, but the error occurs when adding the key to the ord of character.
The first call to getKey(), with your comment:
key = getKey() #Runs function for user to select key. Saves key choice.
Another place you call it:
if userKey < 1 or userKey > 26:
print("Invalid Option. Please try again.")
getKey()
If you were to write that with the same kind of comment, it would be:
getKey() #Runs function for user to select key. Doesn't save key choice.
What the user types in, comes out of getKey() ... and you aren't keeping track of it, so it vanishes. You then do.
return userKey
userKey is still the H you tried to convert to int, the one that failed. You didn't get rid of it, so it's still there.
The better solution is to rework the shape of your code, so getKey() never calls getKey() inside itself. Do the error checking outside, perhaps, like this kind of shape:
def getKey():
prompt user for key
try to convert to int and return the int
if it fails, return None as an indication that getting the key went wrong.
key = None #set some wrong placeholder
while (key is None) or (key < 1) or (key > 26):
key = getKey()
change your input to raw_input
just use the maketrans and translate functions that basically encrypt or decrypt the message for you.they make for a very short and efficient solution to the problem
message = input('enter message').lower()
offset = int(input('enter offset (enter a negative number to decrypt)'))
alphabet = 'abcdefghijklmnopqrstuvwxyz'
enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+ alphabet[0:offset]
data = str.maketrans(alphabet,enc_alphabet)
final_message = str.translate(message, data)
print(final_message)
This code really doesn't need to be this complicated at all, if you just use regex the code will be much shorter but (in my opinion) way better.
Here's a code I created for Caesar cipher encrypting, decrypting and using a shift of the user's choice using regex.
import re
def caesar(plain_text, shift):
cipherText = ''
for ch in plain_text:
stayInAlphabet = ord(ch) + shift
if ch.islower():
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('a'):
stayInAlphabet += 26
elif ch.isupper():
if stayInAlphabet > ord('Z'):
stayInAlphabet -= 26
elif stayInAlphabet < ord('A'):
stayInAlphabet += 26
finalLetter = chr(stayInAlphabet)
cipherText += finalLetter
print(cipherText)
return cipherText
selection = input ("encrypt/decrypt ")
if selection == 'encrypt':
plainText = input("What is your plaintext? ")
shift = (int(input("What is your shift? ")))%26
caesar(plainText, shift)
else:
plainText = input("What is your plaintext? ")
shift = ((int(input("What is your shift? ")))%26)*-1
caesar(plainText, shift)

MySql Database connection with python

I've got an issue trying to connect to a database with python. It compiles without error but it doesn't seem to do anything. I'm not sure if I'm instantiating the class incorrectly or what the issue may be. Could someone point me in the right direction?
import _mysql
import MySQLdb
class Operations:
def open():
db=_mysql.connect("127.0.0.1","root","admin","test")
c=db.cursor()
#deletes the cursor
def close(self):
c.close()
#verifies the credentials and advances
def login(self):
print "Welcome to the online bookstore login!"
x = raw_input('Please enter your user id. ')
y = raw_input('Please enter your password. ')
c.execute("""SELECT userid,password FROM members WHERE userid = %s""", (x,))
z = c.password
if y == z:
member_menu()
else:
close()
def new_user(self):
print "Welcome to the Online book store new user registration page!"
print "To begin, please enter your first name: "
fName = raw_input('Please enter your first name: ')
lName = raw_input('Please enter your last name: ')
address = raw_input('Please enter your street address: ')
city = raw_input('Please enter your city: ')
state = raw_input('Please enter your state: ')
zip_code = raw_input('Please enter your zip code: ')
phone = raw_input('Please enter your phone number: ')
email = raw_input('Please enter your email: ')
user_ID = raw_input('Please enter your user id: ')
password = raw_input('Please enter your password: ')
c.executemany("""INSERT INTO members(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,) VALUES (fName, lName, address, city, state, zip_code, phone, email, user_id, password,)""")
print "Your account has been created. returning to the welcome menu. "
welcome()
def welcome(self):
choice = NONE;
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\tWelcome to the Online Book Store\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Member Login\n"
print "2. New Member Registration\n"
print "3. Quit\n"
choice = raw_input('Type in your option: ')
if choice == 1:
login()
elif x == 2:
new_user()
else:
close()
def member_menu(self):
x = NONE
print "**********************************************************************\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "***\t\t Welcome to the Online Book Store \t\t ***\n"
print "***\t\t\t Member Menu \t\t\t ***\n"
print "***\t\t\t\t\t\t\t\t ***\n"
print "**********************************************************************\n"
print "1. Search by Author/Title/Subject\n"
print "2. View/Edit Shopping Cart\n"
print "3. Check Order Status\n"
print "4. One Click Check Out\n"
print "5. Logout\n"
print "Type in your option: "
x = raw_input('Please enter your choice. ')
if x == 1:
close_conn(),
elif x == 2:
close_conn(),
elif x == 3:
close_conn(),
elif x == 4:
close_conn(),
else:
close_conn()
def main():
start = Operations()
print "Opening conenction to database"
start.welcome
if __name__ == '__main__':
main()
Well, there are so many problems with your code, that I'll probably miss some of them anyway.
Nothing happens, because your main() function and condition are both parts of the class definition, so all the interpreter sees are actually two imports and a class definition.
Let's say we unindented the main() definition and the condition. All that would happen then is creating an instance of Operations (with no special effects, as you have no custom constructor defined) and printing "Opening connection to database" to the screen, because all the last line in main() does is getting a reference to the welcome() method and ignoring it. You need to call it: start.welcome()
When you do call it, much more problems will appear. NameErrors will probably come first, as you are using identifiers that do not exist in given scopes. It seems you're new to Python's object model and probably coming from a language with a different approach, like C++. In Python all non-static and non-class instance methods take a reference to the object they're operating on as the first parameter, traditionally called 'self'. If you want to access any of the fields of the object, you need to do this through 'self', they are not visible to the interpreter otherwise. E.g.: you open a connection and keep the cursor as c, which you later reuse in other methods:
def open():
# ...
c=db.cursor()
# ...
def login(self):
# ...
c.execute("...")
That's incorrect for two reasons:
your open() method does not take self as a parameter
you're creating c as a local variable in scope of the open() method and then trying to access it in login(), which essentialy results in a "reference before assignment" error.
In order to be correct, it should be written like this:
def open(self):
# ...
self.c = db.cursor()
# ...
def login(self):
# ...
self.c.execute("...")
You're making the same mistake in many places. You need to call self.login(), self.new_user(), self.close(), etc.
You're using Python 2, at least according to the question's tags and there is one thing you need to remember when declaring classes in Python 2. There exist so called old- and new-style classes and what you want to do is use the new-style ones. Therefore your class must inherit from object:
class Operations(object):
# ...
They've finally decided to drop the old-style classes support in Python 3 and there's no need to explicitly inherit from object anymore, but while in Python 2, you need to cope with it.
While there are still some errors or potential errors (what is close_connection()?), I think it's enough for a good start ;). Good luck.