Python:来自用户输入的Json文件引用

时间:2015-10-07 07:32:08

标签: python json

我目前正在使用JSON来制作用户名/密码程序,但我遇到了重复帐户的问题。我试图编写一种方法来阻止用户创建JSON数据库已经包含的用户名,但它不能正常工作。

问题

  • 询问用户名,即使尝试的文件为空,也不会要求输入密码

  • 有时会说用户名已存在,但无论如何都会创建帐户副本。

我希望程序做什么

  • 询问新的用户名/密码
  • 如果用户名是唯一的,请将新帐户放入文件
  • 如果用户名已经拥有,请不要添加新帐户并转到功能的开头。

我如何有效地做到这一点? 这是我尝试的代码,但我提到的问题使它无效

def createUser():
    global accounts
    nUsername = input("Create Username »  ")
    for item in accounts:
        if item[0] == nUsername:
            return "Already Exsists!"
        else:
            nPassword = input("Create Password » ")
            entry = [nUsername, nPassword]
            accounts.append(entry)
            accounts = accounts[:500000]
            autoSave()

对于任何想知道的人来说,这就是autosave()功能:

def autoSave():
    with open("Accounts.json", "w") as outfile:
        json.dump(accounts, outfile)

这就是JSON文件内部的样子:

[["ExampleUsername", "BadPasswrdo14130"]]

3 个答案:

答案 0 :(得分:2)

有很多错误,所以我会用评论来解释变化:

# you file containt utf8 chars, you need to specify encoding
# coding=utf-8

import os
import json

# I use a dict structure instead of a list for easier retrieval
# you can easily see if an account exist and get its password
# also global keyword is to avoid, so prefer declaring in the global context instead of pushing to the global context
accounts = {}

# if we have a file, deserialize content
if os.path.exists("/tmp/Accounts.json"):
    try:
        with open("/tmp/Accounts.json") as f:
            accounts = dict(json.loads(f.read()))
    except:
        pass

def createUser():
    # input is equivalent to eval(raw_input(... which is not the goal here
    nUsername = raw_input("Create Username »  ")

    # with a dict, no need to iterate through, simply use `in`
    if nUsername in accounts.keys():
        return createUser()

    nPassword = raw_input("Create Password » ")
    # this is how you assign the new account
    accounts[nUsername] = nPassword
    autoSave()

def autoSave():
    with open("/tmp/Accounts.json", "w") as outfile:
        # we convert here the dict to your list structure
        json.dump(list(accounts.iteritems()), outfile)

def existingUser():
    eUsername = raw_input("Your Username » ")
    ePassword = raw_input("Your Password » ")

    for item in accounts:
        if eUsername in accounts and accounts[eUsername] == ePassword:
            return 'Processing Sucessfully logged into your account!'
        else:
            return "Login failed"

createUser()

答案 1 :(得分:0)

我会这样做:

# This function will help us to check if the user already exists
def alreadyExist(nUsername):
    global accounts
    for account in accounts:
        if account[0] == nUsername
            return True
    return False


def createUser():
    global accounts

    # We declarate nUsername first as None
    nUsername = None

    # While the username exists, we have to ask the user for the username
    while not nUsername or alreadyExist(nUsername):
        nUsername = input("Create Username »  ")

    # We are out of the bucle. The username doesn't exist, we can ask for the password
    nPassword = input("Create Password » ")
    entry = [nUsername, nPassword]
    accounts.append(entry)
    accounts = accounts[:500000]
    autoSave()

答案 2 :(得分:0)

修正了我的代码的一个问题,但又做了另一个问题。在@CyrBill

的机会之前,这部分工作正常
def existingUser():
eUsername = input("Your Username » ")
ePassword = input("Your Password » ")

for item in accounts: #no need for braces
    if item[0] == eUsername and item[1] == ePassword:
        return 'Processing Sucessfully logged into your account!'
    else:
        return "Login failed"