简体   繁体   English

我这样做错了吗?

[英]Am I doing this wrong?

I've just started to learn programming in Python and I'm trying to make a Login System which uses the terminal and stores data into a JSON file and retrieve it to log in.我刚刚开始学习 Python 编程,我正在尝试制作一个登录系统,它使用终端并将数据存储到 JSON 文件中并检索它以登录。

This is the part that looks is causing the problem.这是看起来导致问题的部分。

def login():
    login_username = input("Enter your username: ")
    login_password = input("Enter your pass: ")
    with open("data.json", 'r+') as data:
        if login_username == username and login_password == password:
            print("Successful Login")
        else:
            print("Please Try Again")
            login()

When I am asked for the user and pass and the input matches the data from the JSON it will loop and ask to enter the username and password, again and again.当我被要求输入用户并通过并且输入与来自 JSON 的数据匹配时,它将循环并一次又一次地要求输入用户名和密码。

My whole code is below我的整个代码如下

import json

uname = ""
password =""


def register():
    uname = input("Enter a user to log in with: ")
    password = input("Enter a password: ")
    confirmed_pass = input("Enter the above password again")
    if password != confirmed_pass:
        print("Both the passwords does not match please re-enter a pass")
        password = input("Enter a password:")
        confirmed_pass = input("Enter the above password again")
    login_info = {
        "Username": uname,
        "Password": password
    }
    with open("data.json", "w") as write_file:
        json.dump(login_info, write_file, separators=(',', ':'))
    log = input("Would you like to login? (Y/N)")
    if log == 'Y' or log == "y":
        login()
    else:
        quit()




def login():
    login_uname = input("Enter your username: ")
    login_password = input("Enter your pass: ")
    with open("data.json", 'r') as data:
        if login_uname == uname and login_password == password:
            print("Successful Login")
        else:
            print("Please Try Again")
            login()


reg = input("Have you registered (Y/N) ?:  ")

if reg == 'Y' or reg == 'y':
    login()
elif reg == 'N' or reg == 'n':
    register()
else:
    print("Error!")

Based on your code, you should first use json.loads to load data in to a python dictionary:根据您的代码,您应该首先使用json.loads将数据加载到 python 字典中:

with open("data.json", 'r') as data:
    login = json.loads(data.read())
    # then you can use it like this
    if login_username == login['Username'] and login_password == login['Password']:
        ... Rest of the code

Just a heads your login will only work for last registered user, you should fix that.只是您的登录仅适用于最后注册的用户,您应该解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM