我想在Python中使用JSON来保存用户和密码

时间:2019-01-19 13:34:26

标签: python json python-3.x

这是具有用户登录要求的日记作家。现在,我需要保存用户名和密码,并且每次重新运行该程序时都能够读取它们,因为并非每次用户都将创建其帐户时。

name=[]    
password=[]    
diary=""    
x =""    
namee=""    
passwordd=""    

file = open("user.txt","a")    
print("welcome to world!")    
while x != "q":    
    print("1) Enter :1 sign in!")    
    print("2) Enter :2 create new soul?")    
    print("3) Enter :q exit!")    
    x = input("what do you want?\n")    
    if x == "1":    
        namee=input("Enter your name!")    
        passwordd=input("Enter your password!")    
        if namee in name:    
            if passwordd not in password or name.index(namee) != password.index(passwordd) :    
                print("wrong password")    
            else:    
                file.write("\n\n\n\n")    
                file.write(namee)    
                file.write("\n\n")    
                diary = input("write your diary\n")    
                file.write(diary)    

        else :    
            print("can't find your name here.\n please create new soul!.")    
    elif x =="2":    
        namee = input("enter you name!")    
        if namee in name:    
            print("user name taken")    
        else:    
            passwordd = input("enter your password")    
            name.append(namee)    
            password.append(passwordd)

        elif x=="q":    
        print("thank you for your time")    
    else :    
        print("please enter valid value!")    
print("thanks.!")    
print(name,password)    
file.close()

1 个答案:

答案 0 :(得分:0)

要从json文件中获取要存储的信息(两个列表),只需导入json并加载文件,然后像字典一样对其进行查询即可。

想象一下,像这样的json:

{
    "users": ["Bacon", "Eggs", "Toast"],
    "passwords": ["Please don't do it this way though!", "runny", "buttered"]
}

一个可以简单地:

import json

path_to_json = "./stackoverflowexample.json"

with open(path_to_json, "r") as handler:
    info = json.load(handler)

users = info["users"]
passwords = info["passwords"]

print("User 0 '{}', has password '{}'".format(users[0], passwords[0]))

这是一种非常不安全的密码存储方法,效率非常低,有时您可能会遇到一致性问题。

一种更好的存储密码的方法是在数据库中,这将使您可以更有效地查询所需的信息,并在获得密码时对密码进行加盐和哈希处理,从而不会将其存储为人类可读的密码字符串。

示例:

import sqlite3
import hashlib
import uuid

user_table_definition = """
CREATE TABLE users (
    username TEXT,
    salt TEXT,
    hpassword TEXT
)"""
add_user_sql = "INSERT INTO users VALUES ('{}','{}','{}')"

connection = sqlite3.connect("./stackoverflowdb.db")
cursor = connection.cursor()

cursor.execute(user_table_definition)


# Add incoming user
username = "Bacon"
password = "This is a little better, but this is just an outline..."

salt = uuid.uuid4().hex
hashedpassword = hashlib.sha512((salt + password).encode("UTF-8")).hexdigest()

cursor.execute(add_user_sql.format(username, salt, hashedpassword))

# Check incoming user

username = "Bacon"
password = "This is a little better, but this is just an outline..."

row = cursor.execute("SELECT salt, hpassword FROM users WHERE username = '{}'".format(username)).fetchone()

salt, hpassword = row  # Unpacking the row information - btw this would fail if the username didn't exist

hashedIncomingPwd = hashlib.sha512((salt + password).encode("UTF-8")).hexdigest()

if hashedIncomingPwd == hpassword:
    print("Winner winner chicken dinner we have a live one!")
else:
    print("No access for you")

这仅向您显示了执行所需功能的行,应将其中一些行移入函数中,不能两次调用此代码,因为该表已经创建,并且还有其他问题。首先,您不必使用sqlite!

SQL是一门非常强大的东西,要学习,考虑到您的问题看起来像是一种业余爱好,我建议您继续研究。祝你好运。