【问题标题】:I want to use JSON in Python to save users and password [closed]我想在 Python 中使用 JSON 来保存用户和密码 [关闭]
【发布时间】:2019-01-19 13:34:25
【问题描述】:

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

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

【问题讨论】:

  • 那你试过了吗?发生了什么?你研究过 Python 的 JSON 处理能力吗?
  • 如何使用 json 保存用户名和密码

标签: python json python-3.x


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-27
    • 2013-05-01
    • 2018-03-27
    • 2014-03-08
    • 1970-01-01
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多