2016-01-31 65 views
0

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

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" 

回答

1

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

+0

我把它简化为: 如果“PAS”在基地: enterpass( ) 否则: 打印 “这是数据库的第一起始\ n请输入密码,分5个字符:” 而真: PAS =的raw_input() 如果len(PAS)> 5: 破 基地+ = [{ 'PAS':PAS}] magazine_base [ '基础'] =碱 magazine_base.close() 打印 “密码设定” 否则: 打印 “密码太短,请再输入一次” 但仍然相同,可能通过不读取或保存不正确 – sh4rkyy

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" 

显然,基础是包含条目的列表。每个条目将是一个有'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) 
+0

对不起,我不知道如何实现这个我的代码,即时尝试,但林接收一些关于全局变量和不同的错误。无论如何,我不明白从哪里得到正确的密码,如何设置密码 – sh4rkyy

+0

我不知道它在哪里得到正确的密码!我在查看你的代码,假设你知道密码存储在'base'数据中。 ('getpass'调用从用户那里收集密码,但是它应该与什么进行比较?) –