1. 程式人生 > >python裝飾器之登入練習

python裝飾器之登入練習

#__author: Administrator
#date: 2018/5/21
login_status_jingdong = False
login_status_weixin = False
def start():
    list={1:'home',2:'finance',3:'book'}
    list1={1:home,2:finance,3:book}
    for i in list:
        print(i,list[i])
    select_num =input('請輸入訪問網頁的編號[退出:q]>>')
    if select_num=='q':
        return exit()
    elif select_num.isdigit():
        key=int(select_num)
        list1[key]()
    else:
        print('請輸入有效值!')
def login(auth_type=''):
    def outter(a):
        def inner():
            global login_status_jingdong#獲取全域性變數來實現該變數的賦值修改
            global login_status_weixin
            if auth_type=='jingdong':
                if login_status_jingdong is False:
                    with open('京東賬號', 'r', encoding='utf8') as f1:  # 開啟存有使用者和密碼的檔案只讀模式
                        d1 = {}
                        for i in f1.readlines():
                            [key, valus] = i.split('=')  # 通過分隔符將字串轉為列表,並賦值給變數key和valus
                            d1[key] = valus.strip()  # 向字典中新增元素,這步就實現了字串轉為列表的功能
                    user = input('請輸入使用者名稱>>'.strip())
                    password = input('請輸入密碼>>'.strip())
                    if user == d1['user'] and password == d1['password']:
                        login_status_jingdong= True
                        a()
                    else:
                        print('賬號或密碼錯誤')
                    f1.close()
                else:
                    a()
            elif auth_type=='weixin':
                if login_status_weixin is False:
                    with open('微信賬號', 'r', encoding='utf8') as f2:  # 開啟存有使用者和密碼的檔案只讀模式
                        d2 = {}
                        for i in f2.readlines():
                            [key, valus] = i.split('=')  # 通過分隔符將字串轉為列表,並賦值給變數key和valus
                            d2[key] = valus.strip()  # 向字典中新增元素,這步就實現了字串轉為列表的功能
                    user = input('請輸入使用者名稱>>'.strip())
                    password = input('請輸入密碼>>'.strip())
                    if user == d2['user'] and password == d2['password']:
                        login_status_weixin = True
                        a()
                    else:
                        print('Sorry')
                    f2.close()
                else:
                    a()
        return inner
    return outter
@login('jingdong')
def home():
    print('welcome to home page')
@login('weixin')
def finance():
    print('welcome to finance page')
@login('jingdong')
def book():
    print('welcome to book page')
while True:
    start()