Python,数据库密码

时间:2016-01-31 18:34:14

标签: python database passwords

我正在为类做简单的数据库,我的密码功能有问题。我无法弄清楚为什么每次都要求设置密码。我认为问题在于阅读是否已经在基础但我不知道如何解决它。

import shelve
global base,pas
global magazine_base
def load_data():
    global base
    global magazine_base
    magazine_base = shelve.open('magazine_base')
    if magazine_base.has_key('base'):
        base = magazine_base['base']
        if not base:
            base = []
    else:
        base = []
        magazine_base['base'] = base

def enterpass():
    global base,pas
    epas=raw_input("Enter password to acces database")
    for entry in base:
        while True:
            if epas == entry['pas']:

                break
            else:
                print "Password incorrect"  

def password():
    global base,pas
    global magazine_base
    load_data()

    is_firstopen = True

    if 'pas' in base:
        is_firstopen = False
        enterpass()
    if is_firstopen:
        while True:
            pas=raw_input("This is the first start of database.\nPlease enter the password, min. 5 characters: ")
            if len(pas)>5:
                break
                base += [{'pas':pas}]
                magazine_base['base'] = base
                magazine_base.close()
                print "Password set"
            else:
                print "Password too short"

2 个答案:

答案 0 :(得分:1)

您有提示在无限循环中要求输入密码。

答案 1 :(得分:0)

让我们来看看这个函数:

def enterpass():
    global base,pas
    epas=raw_input("Enter password to acces database")
    for entry in base:
        while True:
            if epas == entry['pas']:
                break
            else:
                print "Password incorrect"  

显然,base是一个包含条目的列表。每个条目都是一个具有键“pas”的字典。如果'pas'条目与用户的密码匹配,则密码有效。我认为如果没有匹配密码是错误的。这不是代码所做的,而是试试这个:

import sys

def enter_password(base):
    """Prompt the user for a password, and validate it against the 
    passwords stored in the entries in base. Permit three tries 
    before terminating the application."""

    from getpass import getpass

    for tries in range(3):
        userpw = getpass("Enter password to access database: ")

        for entry in base:
            if entry['pas'] == userpw:
                return

        print "\nInvalid password!\n"

    print "\nToo many failed password attempts. Goodbye!"
    sys.exit(1)

您可以这样称呼它:

enter_password(base)