如何创建一个用户名和密码系统,以便每次使用该代码时都能记住不同的用户名?

时间:2018-11-13 09:27:51

标签: python python-3.4

我需要创建一个音乐问答游戏,但是只有授权的玩家才能玩该游戏,所以我想让id创建一个用户名和密码系统,但是我该怎么做?

到目前为止,我有这个:

name = input("Please enter your name. ")
age = input("Now please enter you age. ")

username = name[0:3] + age
print ("Your username has been created and 
is", username, ".")

password = input("Now please create a 
password. ")

file = open("Login.txt","a")
file.write (username)
file.write (",")
file.write (password)
file.write("\n")
file.close()

print ("Your login details have been saved")

它会保存创建的用户名和密码,但是我如何创建一个系统,以便用户可以在此之后从存储的用户名和密码中输入他们的用户名和密码?

3 个答案:

答案 0 :(得分:0)

您可以使用字典进行此操作。

import json

create_user():
    global users
    name = input("Please enter your name. ")
    age = input("Now please enter you age. ")

    username = name[0:3] + age
    print ("Your username has been created and is", username, ".")

    password = input("Now please create a  password.")
    users[username] = password
    with open ("Login.txt", 'w') as fd:
        json.dump(users, fd)
    print("Your login details have been saved")

load_users():
    try:
        with open("Login.txt", 'r') as fd:
            users = json.load(fd)
    except:
        print("can't load Login.txt, default dict used")
        users = {}

login():
    username = input("username >")
    password = input("password >")
    if username in users.keys() and password == users[username]:
        print("logged as", username)
        return username
    else
        print("login failed")
        return None
users = load_users()

答案 1 :(得分:0)

一些建议全面展开:

  • 创建时两次询问密码;减轻了处理错字的痛苦
  • 使用getpass.getpass()输入密码
  • 不要将密码存储在文件中。如果数据库太麻烦了,请使用单向哈希函数。

现在,假设您仍然想在没有数据库的情况下继续操作,那么更简单的方法可能是将用户名-密码对以字典格式存储在[例如]泡菜对象中。每次您要求有人登录时,要求输入用户名,然后检查字典键中是否存在该用户名。如果找到密钥,则要求输入密码,并将其与密钥对应的值匹配。

from getpass import getpass
import os, pickle, hashlib
userdata = dict()
if os.path.exists('userinfo.pickle'):
    userdata = pickle.load(open('userinfo.pickle','rb'))
username = raw_input("Enter username:")
pwd = getpass("Enter password:")
pwd2 = getpass("Enter password again:")
if pwd != pwd2:
    exit(0)
h = hashlib.md5()
h.update(pwd)
pwd = h.hexdigest()
if username not in userdata:
    userdata[username] = pwd
with open('userinfo.pickle','wb') as handle:
    pickle.dump(userdata,handle)

# Logging in
userdata = pickle.load(open('userinfo.pickle','rb'))
username = raw_input("Enter username:")
pwd = getpass("Enter password:")
h = hashlib.md5()
h.update(pwd)
pwd = h.hexdigest()
if username in userdata:
    if userdata[username] == pwd:
        print("Success.")
    else:
        print("Incorrect password.")
else:
    print("User not found.")

这应该做到。

答案 2 :(得分:0)

我认为您最好使用CSV来分隔名称和用户名,这将使搜索用户名和密码对更加容易。如果您想使用此功能,则应该可以进行以下操作:

创建用户名/密码:

import pandas as pd

userpass = pd.read_csv('Login.csv')
name = input("Please enter your name. ")
age = input("Now please enter you age. ")

username = name[0:3] + age
print ("Your username has been created and 
is", username, ".")

password = input("Now please create a 
password. ")

newuserpass = [(username, password)]
newuserpass = pd.DataFrame(newuserpass) #Creates a dataframe of username & pass
userpass = userpass.append(newuserpass) #Adds username and pass dataframe to end of username/password save file
userpass.to_csv('Login.csv')
'''This has now saved the login details. Now to read the login details, where pandas makes this quite easy'''

正在加载用户名/密码:

loggedin = 0
while loggedin = 0:
    userpass = pd.read_csv('Login.csv')
    inputusername = input('What is your username?')
    inputpassword = input('What is your password?')




    if userpass.Password.values[userpass.Username==inputusername] == inputpassword:
      userpass = 1
      print('Logged in successfully!')

在此代码生效之前,您需要创建一个名为“ Login.csv”的空白文件,其中包含用户名和密码。