7-1 字典方法。那个字典方法可以用来把两个字典合并到一起
dict1.update(dict2)
7–5. userpw2.py.
下面的问题和例题7.1 中管理名字-密码的键值对数据的程序有关。
(a)修改那个脚本,使它能记录用户上次的登录日期和时间(用time 模块),并与用户密码一起保存起来。程序的界面有要求用户输入用户名和密码的提示。无论户名是否成功登录,都应有提示,在户名成功登录后,应更新相应用户的上次登录时间戳。如果本次登录与上次登录在时间上相差不超过4 个小时,则通知该用户: “You already logged in at: <last_ login_timestamp>.”
(b) 添加一个“管理”菜单,其中有以下两项:(1)删除一个用户 (2)显示系统中所有用户的名字和他们的密码的清单。
(c) 口令目前没有加密。请添加一段对口令加密的代码(请参考crypt, rotor, 或其它加密模块)
(d) 为程序添加图形界面,例如,用Tkinter 写。
(e) 要求用户名不区分大小写。
(f) 加强对用户名的限制,不允许符号和空白符。
(g)合并“新用户”和“老用户”两个选项。如果一个新用户试图用一个不存在的用户名登录,
询问该用户是否是新用户,如果回答是肯定的,就创建该帐户。否则,按照老用户的方式登录。
from datetime import datetime
import hashlib
db={}
def newuser():
value=[]
prompt='login name desired again: '
while True:
name=raw_input(prompt).lower()
if not name.isalnum() and '' in name:
print 'name format error'
continue
else:
if db.has_key(name):
prompt='name taken,try another: '
continue
else:
break
pwd=raw_input('login passwd desired: ')
m=hashlib.md5()
m.update(pwd)
value.append(m.hexdigest())
value.append(datetime.now())
db[name]=value
print 'new user is %s, register time is %s' %(name,db[name][1])
def olduser():
name=raw_input('login name desired again: ').lower()
pwd=raw_input('login passwd desired: ')
m=hashlib.md5()
m.update(pwd)
passwd=db.get(name)
if passwd[0]==m.hexdigest():
newtime=datetime.now()
if (newtime-db[name][1]).days==0 and (newtime-db[name][1]).seconds<14400:
print 'you already logged in at %s: ' %(db[name][1])
else:
passwd[1]=newtime
print 'welcome back %s, login time is %s' %(name,passwd[1])
else:
print 'login incorrect'
def removeuser():
print db
name=raw_input('input a user name to remove: ').lower()
if name in db:
db.pop(name)
else:
print 'input error'
def userlogin():
while True:
name=raw_input('login name desired: ').lower()
if not name.isalnum() and '' in name:
print 'name format error'
continue
else:
if not db.has_key(name):
print 'user name is not in db'
answer=raw_input('register a new user? y/n').lower()
if 'y'==answer:
newuser()
break
elif 'n'==answer:
break
else:
print 'user name is already in db'
olduser()
break
def showmenu():
prompt="""
(U)ser Login
(R)emove a existing user
(Q)uit
Enter choice:"""
done=False
while not done:
chosen=False
while not chosen:
try:
choice=raw_input(prompt).strip()[0].l