2016-01-31 85 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'調用從用戶那裏收集密碼,但是它應該與什麼進行比較?) –