python学习之成员信息增删改查

主要实现了成员信息的增加,修改,查询,和删除功能,写着玩玩,
在写的过程中,遇到的问题,旧新成员信息数据的合并,手机号和邮箱的验证,


#!/usr/bin/env python
# coding=utf8
#author:shantuwqk@163.com


import os, sys, time,json
import re


member_dict = \
{}
member_name_list = []
member_list = []
def handler_member_storage(name,passwd,mobile,email):

member_detailed = {}
member_detailed['name'] = name
member_detailed['passwd'] = passwd
member_detailed['mobile'] = mobile
member_detailed['email'] = email
member_list.append(member_detailed)
member_name_list.append(name)
member_dict['namelist'] = member_name_list
member_dict['namedetail'] = member_list
#with open('member_info.json','w') as f:
# json.dump(member_dict,f)
return member_dict


def handel_query_user(x):
"""
判断x如果是str,查询name字段,如果是int,查询手机号字段
:param x:
:return:
"""
#print "字符串",isinstance(x,str)
#print "数字",isinstance(x,int)
if isinstance(x,str):
if x in load_member_data()['namelist']:
print "精确匹配查询用户[%s]信息....."%(x)
print "==================================================="
user_index = load_member_data()['namelist'].index(x)
user_detail = load_member_data()['namedetail'][user_index]
for k,v in user_detail.items():
print k,v
print "----------------------------------------------------"
else:
print "\033[33;1m用户名或密码不在本数据库,你是不是记错了?您再想想!!\033[0m"

if isinstance(x,int):
if check_mobileORmail_member(str(x)) != "mobile_true":
print "这是手机号吗,打打试试...."
else:
print "精确匹配查询用户手机[%s]信息......"%(x)
print "===================================================="
user_detail = load_member_data()['namedetail']
for user_dict in user_detail:
if x == int(user_dict['mobile']):
for k,v in user_dict.items():
print k,v
print "------------------------------------------------"


def load_member_data():
with open("member_info.json",'r') as f:
try:
member_info_dict = json.load(f)
return member_info_dict
except ValueError:
#print "\033[33;1m没有数据可加载\033[0m"
return False



def check_login(user,passwd):
"""
验证登录用户名和密码是否正确
:param user:
:param passwd:
:return:
"""
with open("member_info.json",'r') as f:
member_info_dict = json.load(f)
#print member_info_dict
if user in member_info_dict['namelist']:
user_index = member_info_dict['namelist'].index(user)
user_detail = member_info_dict['namedetail'][user_index]
#print user_index,user_detail
if passwd == user_detail['passwd'] and user == user_detail['name']:
print "\033[32;1m输入用户[%s]密码[%s]正确\033[0m"%(user,passwd)
return True
else:
print "\033[31;1m 您输入的密码不正确\033[0m"
else:
print "\033[31;1m你查询的用户不存在\033[0m"




def check_mobileORmail_member(x):
p=re.compile(r'^[\w\d]+[\d\w\_\.]+@([\d\w]+)\.([\d\w]+)(?:\.[\d\w]+)?$|^(?:\+86)?(\d{3})\d{8}$|^(?:\+86)?(0\d{2,3})\d{7,8}$')
m = p.match(x)
if m == None:
print "\033[33;1mmail or mobile number is wrong!!\033[0m"
return False
else:
if m.group(1)!=None:
if m.group(1) == 'vip':
print 'It is %s mail,the address is %s' %(m.group(2),m.group())
return "mail_true"
else:
print 'It is %s mail,the address is %s' %(m.group(1),m.group())
return "mail_true"
else:
if m.group(3)!=None:
print 'It is mobilephone number,the number is %s' %m.group()
return "mobile_true"
else:
print 'It is telephone number,the number is %s' %m.group()
return True

class Modify_User_Info:
"""
修改用户的相关信息
"""
def update_passwd(self,user,newpwd):
if user in load_member_data()['namelist']:
user_index = load_member_data()['namelist'].index(user)
user_detail = load_member_data()['namedetail'][user_index]
user_detail['passwd'] = newpwd
newpwd_dict = load_member_data()
newpwd_dict['namedetail'][user_index] = user_detail
return newpwd_dict
else:
print "你有没有搞错!你输入的用户不在数据库"



def update_mobile(self,user,newmobile):
if user in load_member_data()['namelist']:
user_index = load_member_data()['namelist'].index(user)
user_detail = load_member_data()['namedetail'][user_index]
user_detail['mobile'] = newmobile
newpwd_dict = load_member_data()
newpwd_dict['namedetail'][user_index] = user_detail
return newpwd_dict
else:
print "你有没有搞错!你输入的用户不在数据库"


def update_email(self,user,newmail):
if user in load_member_data()['namelist']:
user_index = load_member_data()['namelist'].index(user)
user_detail = load_member_data()['namedetail'][user_index]
user_detail['email'] = newmail
newpwd_dict = load_member_data()
newpwd_dict['namedetail'][user_index] = user_detail
return newpwd_dict
else:
print "你有没有搞错!你输入的用户不在数据库"

def del_user_info(user):
if user in load_member_data()['namelist']:
user_index = load_member_data()['namelist'].index(user)
user_detail = load_member_data()['namedetail'][user_index]
new_del_dict = load_member_data()
new_del_dict['namedetail'].remove(user_detail)
new_del_dict['namelist'].remove(user)
return new_del_dict

else:
print "你要删除的用户[%s]不在数据库里"%user





if __name__ == "__main__":
Operation_type = {
'1':'Add user information',
'1.1':'name,passwd,mobile,email',
'2':'Query the user information',
'3':'Modify the user information',
'4':'Delete user information',
'5':'logout'
}


while True:
print """
\033[32;1m********************************************************************************
Welcome to login user information center, you can make the following operation:
1,%s
2,%s
3,%s
4,%s
5,%s
What you need to operate?
********************************************************************************\033[0m
"""%(Operation_type['1'],Operation_type['2'],Operation_type['3'],Operation_type['4'],Operation_type['5'])
option = raw_input("Choice is?>>")

if option == '1':
print "\033[32;1m you have choice is [%s]\033[0m"%Operation_type['1']
print "You need to complete these input according to [%s] the guidelines"%Operation_type['1.1']
while True:
name = raw_input("name:")
passwd = raw_input("passwd:")
mobile = raw_input("mobile:")
email = raw_input("email:")
if len(name) == 0 or len(passwd) == 0 or len(mobile) == 0 or len(email) == 0:
print "\033[33;1mThe user information you entered any item can't be empty or incorrect.Please fill in again!!\033[0m"
continue
if check_mobileORmail_member(mobile) != "mobile_true" or check_mobileORmail_member(email) != "mail_true":
continue

#print "#########3",name,passwd,mobile,email

print """\033[32;1m 您输入的信息如下:
name:%s
passwd:%s
mobile:%s
email:%s
\033[0m"""%(name,passwd,mobile,email)
s1 = raw_input("y 保存/w 重新填写>>")
if s1 == "y":

old_user_dict = load_member_data()
new_user_dict = handler_member_storage(name,passwd,mobile,email)
#print "############33",old_user_dict,'\n',new_user_dict
#合并旧的和新的用户数据
if old_user_dict == False:
print "没有旧数据可加载,直接写入新数据"
with open('member_info.json','w') as f:
json.dump(new_user_dict,f)
s11 = raw_input("t 继续添加/b 返回上一级/q退出操作?>>")
if s11 == "t":
continue
elif s11 == "b":
break
elif s11 == "q":
sys.exit(0)
else:
for user in new_user_dict['namelist']:
old_user_dict['namelist'].append(user)
for user_detail in new_user_dict['namedetail']:
old_user_dict['namedetail'].append(user_detail)
#print old_user_dict,
with open('member_info.json','w') as f:
json.dump(old_user_dict,f)
print "保存成功"
s12 = raw_input("t 继续添加/b 返回上一级/q退出操作?>>")
if s12 == "t":
continue
elif s12 == "b":
break
elif s12 == "q":
sys.exit(0)
elif s1 == "w":
continue
else:
pass

elif option == '2':
print "\033[32;1m you have choice is [%s]\033[0m"%Operation_type['2']
print "\033[33;1m友情提示:输入正确的用户名和密码才能查询用户信息\033[0m"
luser = raw_input("用户名:").strip()
lpasswd = raw_input("用户密码:").strip()
if check_login(luser,lpasswd) == True:
print "用户验证通过"
print "请输入需要查询的用户名或手机号[目前只支持精确查询]"
while True:
query_info = raw_input("查询:>>").strip()
if check_mobileORmail_member(query_info) == "mobile_true":
handel_query_user(int(query_info))
else:
handel_query_user(query_info)
s2 = raw_input("b 返回上一级/t 继续查询")
if s2 == "b":
break
elif s2 == "t":
continue

else:
print "用户名或密码不正确,不能查询其它人信息"




elif option == '3':
print "\033[32;1m you have choice is [%s]\033[0m"%Operation_type['3']
print "友情提示:目前支持修改用户的密码,手机号,邮箱地址"
modify = Modify_User_Info()
modify_option = raw_input("p 修改密码/m 修改手机号/e 修改邮箱地址")
if modify_option == "p":
user_name = raw_input("用户名:").strip()
user_pwd = raw_input("新密码:").strip()
print "开始修改用户[%s]新的密码为[%s]....."%(user_name,user_pwd)
update_dict = modify.update_passwd(user_name,user_pwd)
with open('member_info.json','w') as f:
json.dump(update_dict,f)
print "密码修改成功!"
elif modify_option == "m":
user_name = raw_input("用户名:").strip()
user_mobile = raw_input("新手机号:").strip()
print "开始修改用户[%s]新的手机号为[%s]....."%(user_name,user_mobile)
update_dict = modify.update_mobile(user_name,user_mobile)
with open('member_info.json','w') as f:
json.dump(update_dict,f)
print "手机号修改成功!"
elif modify_option == "e":
user_name = raw_input("用户名:").strip()
user_mail = raw_input("新邮箱:").strip()
print "开始修改用户[%s]新的邮箱为[%s]....."%(user_name,user_mail)
update_dict = modify.update_email(user_name,user_mail)
with open('member_info.json','w') as f:
json.dump(update_dict,f)
print "邮箱修改成功!"

elif option == '4':
print "\033[32;1m you have choice is [%s]\033[0m"%Operation_type['4']
print "友情提示:请输入用户名"
user_name = raw_input("用户名:")
new_del_dict = del_user_info(user_name)
with open('member_info.json','w') as f:
json.dump(new_del_dict,f)
print "用户[%s]删除成功!!"%(user_name)
elif option == '5':
print "\033[32;1m you have choice is [%s]\033[0m"%Operation_type['5']
sys.exit(0)
else:
print "\033[31;1m The choice of the invalid \033[0m"

#print check_mobileORmail_member('123456')
#print check_login('testwqk','testwqk')
#print handel_query_user(18600404875)







posted @ 2015-07-20 10:10  shantuwqk  阅读(373)  评论(0编辑  收藏  举报