Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我想在Python中使用JSON来保存用户和密码_Python_Json_Python 3.x - Fatal编程技术网

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

我想在Python中使用JSON来保存用户和密码,python,json,python-3.x,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) Ente

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

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()

要从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是一种非常强大的学习工具,考虑到您的问题看起来像是一种爱好,我建议您边学习边研究。祝你好运。

你试过了吗?怎么搞的?你研究过Python的JSON处理功能吗?我如何使用JSON保存用户名和密码