def supplier_registeration
print "Registration form :"
print "\nName :"
name = gets.chomp.downcase
print "User Name :"
user_name = gets.chomp.downcase
print "Password :"
password = gets.chomp.downcase
print "contact :"
contact = gets.chomp.to_i
print "address :"
address = gets.chomp.downcase
CSV.open("source/supplier.csv", "wb") do |csv|
csv << ["name", "user name", "password", "contact", "address"]
csv << [name, user_name, password, contact, address]
end
print "Registration successfully..!\n"
supplier
end
This method writes to the CSV file, but on the next registration entry, my file rewrites the initial data. How do I append user input to the next line automatically?
this is the answer for above question
'headers = ['name','user name','password','contact','address']
CSV.open('source/consumer_list.csv', 'a+', {force_quotes: true}) do |csv|
csv << headers if csv.count.eql? 0
csv << [name, user_name, password, contact, address]
end'
Related
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()
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.
Inside of a json file, each line stores the information of every different user that is created through separate classes. In the user_login file, retrieves this info and isolates username and passwords for each user to attempt to create a login page.
File: user_login
import json
filename = "users.json"
with open(filename, "r+", encoding='utf8') as file:
'''opens json file and separates it by line by storing each line into an
array'''
lines = file.readlines()
login_info = {}
'''array that will store usernames and passwords for each user(each line in
the file is a user)'''
for line in lines:
'''simply prints each element of the lines array displaying the
information of each user'''
info = json.loads(line)
print("USER: " + str(info))
print("username: " + info["username"])
print("password: " + info["password"] + "\n")
login_info[info["username"]] = info["password"]
'''creates a new pair of username and password for each user(each line is
a user)'''
print(login_info)
print(lines)
print(login_info)
'''prompts user for their username and password'''
prompt_username = input("Please enter username: ")
prompt_password = input("Please input password: ")
The problem is in the following method(it does not work):
def login(username, password):
'''if username exists and the inputed strings match one of the key-value
pairs, login is successful'''
if username in login_info:
if password == info["password"]:
print("LOGIN SUCCESSFUL")
else:
print("Sorry, password does not exist.")
else:
print("Sorry this username or password does not exist.")
login(prompt_username, prompt_password)
How do I effectively check if the user inputs for username and password match any of the dictionary pairs to simulate a login?
The following is the users.json file.
File: users.json
{"first": "Gilberto", "last": "Robles", "username": "girobles1", "password": "1234", "location": "San Diego", "interests": [["eat", "sleep", "code", "repeat"]]}
{"first": "Gilberto", "last": "Robles", "username": "girobles2", "password": "12345", "location": "San Diego", "interests": [["eat", "sleep", "code"]]}
It looks like you're just calling the wrong object to check if the password is correct
if password == info["password"]:
should be
if password == login_info[username]:
Follow-up question about number of attempts:
I rewrote your function to return the status of the username and password accuracy:
def login(username, password):
'''if username exists and the inputed strings match one of the key-value
pairs, login is successful returns (Username Correct, Password Correct)'''
if username in login_info:
if password == login_info[username]:
print("LOGIN SUCCESSFUL")
return (True, True)
else:
print("Sorry, password does not exist.")
return (True, False)
else:
print("Sorry this username does not exist.")
return (False, False)
login(prompt_username, prompt_password)
Then added a loop to check the results and logic to handle them (This is untested, since I don't have your dictionary):
'''prompts user for their username and password'''
username_attempts = 3
password_attempts = 3
prompt_username = input("Please enter username: ")
prompt_password = input("Please input password: ")
username_guess = 1
password_guess = 1
while True: #Loops until broken
if username_guess > username_attempts:
print("Too many invalid usernames, goodbye")
#What do you want it to do if they fail?
break
if password_guess > password_attempts:
print("Too many invalid passwords, goodbye")
#What do you want it to do if they fail?
break
username_status, password_status = login(prompt_username, prompt_password)
if all([username_status, password_status]):
break
elif not username_status:
print("Invalid username, please try again")
prompt_username = input("Please enter username: ")
username_guess += 1
elif not password_status:
print("Invalid password, please try again")
prompt_password = input("Please input password: ")
password_guess += 1
I have a piece of code that takes an entered number, searches a CSV and outputs that line, however the original entered number is also printed. What would I need to modify in my code to remove this ?
def DoASearch():
self.outputQty.delete(1.0, 'end')
self.outputDesc.delete(1.0, 'end')
self.dwgoutputbox.configure(state="normal")
self.dwgoutputbox.delete(1.0, 'end')
self.dwgoutputbox.configure(state="disabled")
try:
print(int(sonumber.get()))
except ValueError:
messagebox.showwarning("OPPS !!", "Please enter a valid Shop Order number.")
with open("lesspreadsheettest.csv") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
result=(row['Shop Order'])
if sonumber.get() == result:
print(row['Part Number'])
print(row['Description'])
print(row['Quantity'])
print(row['Drawings'])
print(row['Issue'])
self.searchbutton = ttk.Button(rootWindow, text="Search", command=DoASearch)
self.searchbutton.grid(row=1, column=7, sticky=W, padx=3, pady=3)
Modified and works nicely with the below code. Theres a few extra repeat fields that have been added which can be ignored.
def checkcsv():
with open("lesspreadsheettest.csv") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
result=(row['Shop Order'])
if sonumber.get() == result:
descQty=(row['Quantity'])
descInfo=(row['Description'])
descPN=(row['Part Number'])
descDwg1=(row['Drawings1'])
descIss1=(row['Issue1'])
descDwg2=(row['Drawings2'])
descIss2=(row['Issue2'])
descDwg3=(row['Drawings3'])
descIss3=(row['Issue3'])
self.outputQty.insert(INSERT,descQty)
self.outputDesc.insert(INSERT,descPN, END," ", END, descInfo)
self.dwgoutputbox.insert(INSERT, descDwg1, END, " ", END, " Issue: ",END,descIss1,END, "\n")
self.dwgoutputbox.insert(INSERT, descDwg2, END, " ", END, " Issue: ",END,descIss2,END, "\n")
self.dwgoutputbox.insert(INSERT, descDwg3, END, " ", END, " Issue: ",END,descIss3,END, "\n")
self.outputQty.configure(state="disabled")
self.outputDesc.configure(state="disabled")
self.dwgoutputbox.configure(state="disabled")
A slightly better version using a loop follows:
def checkcsv():
with open("lesspreadsheettest.csv") as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
result=(row['Shop Order'])
if sonumber.get() == result:
descQty=(row['Quantity'])
descInfo=(row['Description'])
descPN=(row['Part Number'])
for i in range(1,4):
descDwg=(row['Drawings'+ str(i)])
descIss=(row['Issue'+ str(i)])
self.dwgoutputbox.insert(1.0, descDwg, "dwg", " Issue: ", "", descIss, "", "\n")
self.outputQty.insert(1.0, descQty)
self.outputDesc.insert(1.0, descPN, "", ": ", "", descInfo)
self.outputQty.configure(state="disabled")
self.outputDesc.configure(state="disabled")
self.dwgoutputbox.configure(state="disabled")
I suggest to change the following line
print(int(sonumber.get()))
into
int(sonumber.get())
However, you should really take a deeper look at your code in order to understand which things it does and where it does those things.
I am trying to save the below kind of CSV records into a DB:
9,Lambert,Kent D,Senator
But it is not being saved in DB, the transaction is being rollbacked and giving this error.
{"state_senate_district_id"=>"9", "last_name"=>"Lambert", "first_name"=>"Kent D", "tag"=>"Senator"}
(0.2ms) BEGIN
(0.1ms) ROLLBACK
["First name should contain only alphabets"]
So there is a space in first_name = "Kent D", hence it is not allowing space, so it's not saving to the DB.
Below is the code to parse the CSV:
hash = {}
CSV.foreach('Senator.csv', {:headers=>:first_row}) do |line|
hash['state_senate_district_id'] = line[0]
hash['last_name'] = line[1]
hash['first_name'] = line[2]
hash['tag'] = line[3]
puts hash
senator = Senator.new(hash)
unless senator.save(hash)
err = senator.errors.full_messages
p err
File.open("errors", "a") do |csv|
err.each do |c|
csv << "\n"
csv << "||||||"
csv << [c]
end
end
end
You probably have a validation rule in the Senator model that is preventing the first_name field from having a space. Remove that validation or change it so that it allows spaces.