zoukankan      html  css  js  c++  java
  • 26.本章小结

    练习题

    参考答案:http://www.cnblogs.com/alice-bj/p/8485985.html

    1. logging模块有几个日志级别?
    2. 请配置logging模块,使其在屏幕和文件里同时打印以下格式的日志

      2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts
      
    3. json、pickle、shelve三个区别是什么?

    4. json的作用是什么?
    5. subprocess执行命令方法有几种?
    6. 为什么要设计好目录结构?
    7. 打印出命令行的第一个参数。例如:

      python argument.py luffy
      打印出 luffy
      
    8. 代码如下:

      '''
      Linux当前目录/usr/local/nginx/html/
      文件名:index.html
      '''
      import os
      BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(index.html)))
      print(BASE_DIR)
      
      1. 打印的内容是什么?
      2. os.path.dirname和os.path.abspath含义是什么?
    9. 通过configparser模块完成以下功能

      文件名my.cnf

      [DEFAULT]
      
      [client]
      port = 3306
      socket = /data/mysql_3306/mysql.sock
      
      [mysqld]
      explicit_defaults_for_timestamp
      port = 3306
      socket = /data/mysql_3306/mysql.sock
      back_log = 80
      basedir = /usr/local/mysql
      tmpdir = /tmp
      datadir = /data/mysql_3306
      default-time-zone = '+8:00'
      
      1. 修改时区 default-time-zone = '+8:00' 为 校准的全球时间 +00:00
      2. 删除 explicit_defaults_for_timestamp
      3. 为DEFAULT增加一条 character-set-server = utf8
    10. 写一个6位随机验证码程序(使用random模块),要求验证码中至少包含一个数字、一个小写字母、一个大写字母.

    11. 利用正则表达式提取到 luffycity.com ,内容如下

      <!DOCTYPE html>
      <html lang="en">
      <head>
         <meta charset="UTF-8">
         <title>luffycity.com</title>
      </head>
      <body>
      </body>
      </html>
      
    12. 写一个用户登录验证程序,文件如下
      1234.json

      {"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
      
      1. 用户名为json文件名,密码为 password。
      2. 判断是否过期,与expire_date进行对比。
      3. 登陆成功后,打印“登陆成功”,三次登陆失败,status值改为1,并且锁定账号。
    13. 把第12题三次验证的密码进行hashlib加密处理。即:json文件保存为md5的值,然后用md5的值进行验证。

    14. 最近luffy买了个tesla,通过转账的形式,并且支付了5%的手续费,tesla价格为75万。文件为json,请用程序实现该转账行为。
      需求如下:

      1. 目录结构为
      .
      ├── account
      │   ├── luffy.json
      │   └── tesla.json
      └── bin
            └── start.py
      

      当执行start.py时,出现交互窗口

         ------- Luffy Bank ---------
        1.  账户信息
        2.  转账
      
      • 选择1 账户信息 显示luffy的当前账户余额。
      • 选择2 转账 直接扣掉75万和利息费用并且tesla账户增加75万
    15. 对上题增加一个需求:提现。
      目录结构如下

      .
      ├── account
      │   └── luffy.json
      ├── bin
      │   └── start.py
      └── core
         └── withdraw.py
      

      当执行start.py时,出现交互窗口

         ------- Luffy Bank ---------
      1.  账户信息
      2.  提现
      
      • 选择1 账户信息 显示luffy的当前账户余额和信用额度。
      • 选择2 提现 提现金额应小于等于信用额度,利息为5%,提现金额为用户自定义。
    16. 尝试把上一章的验证用户登陆的装饰器添加到提现和转账的功能上。

    17. 对第15题的用户转账、登录、提现操作均通过logging模块记录日志,日志文件位置如下

       .
       ├── account
       │   └── luffy.json
       ├── bin
       │   └── start.py
       └── core
       |   └── withdraw.py
       └── logs
           └── bank.log
      

     

    答案

    12、用户验证

    # 用户名为json文件名,密码为 password。
    # 判断是否过期,与expire_date进行对比。
    # 登陆成功后,打印“登陆成功”,三次登陆失败,status值改为1,并且锁定账号。
    
    # {"expire_date": "2021-01-01", "id": 1234, "status": 0, "pay_day": 22, "password": "abc"}
    
    import time
    import json
    import re
    
    # 取出用户名
    json_name = '1234.json'
    username = re.split('.json$', json_name)[0]
    
    # 取出locker用户
    f = open('locker', 'r')
    lockers = f.read()
    locker_list = lockers.split()
    f.close()
    
    # json数据 取出 密码、状态、过期时间
    f = open(json_name, 'r')
    data = json.load(f)
    password = data['password']
    expire_date = data['expire_date']
    status = data['status']
    
    # 过期时间转换格式
    expire_date = time.strptime(expire_date, "%Y-%m-%d")
    expire_date = time.mktime(expire_date)
    now_date = time.time()
    
    count = 0
    while True:
        _username = input('用户名:').strip()
        _password = input('密码:').strip()
        if _username not in locker_list:
            if username == _username and password == _password:
                if now_date < expire_date:
                    print('welcome')
                else:
                    print('密码过期')
            else:
                print('用户名或密码错误')
        else:
            print('用户名已经被锁定')
    
        count += 1
        if count == 3:
            # 锁定用户
            f = open('locker', 'a')
            f.write(_username+'	')
            f.close()
            print('该用户已经被锁定')
    
            # status修改为0,写入json
            data['status'] = 1
            f = open(json_name, 'w')
            json.dump(data, f)
            f.close()
            break
    View Code

    13、md5加密

    import hashlib
    pwd_md5_1 = '202cb962ac59075b964b07152d234b70'
    print(pwd_md5_1)
    
    _password = input('密码:').strip()
    m = hashlib.md5()
    m.update(_password.encode())
    pwd_md5 = m.hexdigest()
    print(pwd_md5)
    
    if pwd_md5_1 == pwd_md5:
        print('ok')
    # 用户名为json文件名,密码为 password。
    # 判断是否过期,与expire_date进行对比。
    # 登陆成功后,打印“登陆成功”,三次登陆失败,status值改为1,并且锁定账号。
    
    # 把第12题三次验证的密码进行hashlib加密处理。即:json文件保存为md5的值,然后用md5的值进行验证。
    
    import time
    import json
    import re
    import hashlib
    
    # 取出用户名
    json_name = '1234.json'
    username = re.split('.json$', json_name)[0]
    
    # 取出locker用户
    f = open('locker', 'r')
    lockers = f.read()
    locker_list = lockers.split()
    f.close()
    
    # json数据 取出 密码、状态、过期时间
    f = open(json_name, 'r')
    data = json.load(f)
    password = data['password']
    expire_date = data['expire_date']
    status = data['status']
    # print(password)
    
    # 过期时间转换格式
    expire_date = time.strptime(expire_date, "%Y-%m-%d")
    expire_date = time.mktime(expire_date)
    now_date = time.time()
    
    count = 0
    while True:
        _username = input('用户名:').strip()
        _password = input('密码:').strip()
    
        # 密码的md5值
        m = hashlib.md5()
        m.update(_password.encode())
        pwd_md5 = m.hexdigest()
    
        if _username not in locker_list:
            if username == _username and password == pwd_md5:
                if now_date < expire_date:
                    print('welcome')
                    break
                else:
                    print('密码过期')
            else:
                print('用户名或密码错误')
        else:
            print('用户名已经被锁定')
    
        count += 1
        if count == 3:
            # 锁定用户
            f = open('locker', 'a')
            f.write(_username + '	')
            f.close()
            print('该用户已经被锁定')
    
            # status修改为0,写入json
            data['status'] = 1
            f = open(json_name, 'w')
            json.dump(data, f)
            f.close()
            break
    View Code

    14、转账

    # 最近luffy买了个tesla,通过转账的形式,并且支付了5%的手续费,tesla价格为75万。文件为json,请用程序实现该转账行为。
    # 需求如下:
    #
    # 目录结构为
    # .
    # ├── account
    # │   ├── luffy.json
    # │   └── tesla.json
    # └── bin
    #       └── start.py
    # 当执行start.py时,出现交互窗口
    #
    #    ------- Luffy Bank ---------
    #   1.  账户信息
    #   2.  转账
    # 选择1 账户信息 显示luffy的当前账户余额。
    # 选择2 转账 直接扣掉75万和利息费用并且tesla账户增加75万
    
    import os
    import sys
    
    # 取出当前文件的父目录,
    print(__file__)
    BASE_DIR = os.path.abspath(__file__)
    print(BASE_DIR)
    BASE_DIR1 = os.path.dirname(BASE_DIR)
    print(BASE_DIR1)
    BASE_DIR2 = os.path.dirname(BASE_DIR1)
    print(BASE_DIR2)
    
    # 取出json文件的绝对路径
    file_path1 = BASE_DIR2 + "\" + "account" + "\" + "luffy.json"
    file_path2 = BASE_DIR2 + "\" + "account" + "\" + "tesla.json"
    
    
    
    msg = """
        ------- Luffy Bank ---------
        1.  账户信息
        2.  转账
      """
    
    print(msg)
    price = 75000
    print(price)
    choice = int(input('>'))
    
    import json
    if choice == 1:
        f = open(file_path1, 'r')
        data = json.load(f)
        f.close()
        print('账户余额:', data)
    
    elif choice == 2:
    
        # tesla.json 文件操作
        f = open(file_path2, 'r+')
        data = json.load(f)
        data += price
        f.seek(0)
        json.dump(data,f)
        f.close()
    
        fin_price = price *(1 + 5/100 )
        print('你购买了tesla,花费了', fin_price)
    
        # luffy.json 文件操作
        f = open(file_path1, 'r+')
        data = json.load(f)
        data -= price
        print('余额剩下', data)
        f.seek(0)
        json.dump(data, f)
        f.close()
    View Code

    15、提现

    # 最近luffy买了个tesla,通过转账的形式,并且支付了5%的手续费,tesla价格为75万。文件为json,请用程序实现该转账行为。
    # 需求如下:
    #
    # 目录结构为
    # .
    # ├── account
    # │   ├── luffy.json
    # │   └── tesla.json
    # └── bin
    #       └── start.py
    # 当执行start.py时,出现交互窗口
    #
    #    ------- Luffy Bank ---------
    #   1.  账户信息
    #   2.  转账
    # 选择1 账户信息 显示luffy的当前账户余额。
    # 选择2 转账 直接扣掉75万和利息费用并且tesla账户增加75万
    
    # 对上题增加一个需求:提现。
    # 目录结构如下
    #
    # .
    # ├── account
    # │   └── luffy.json
    # ├── bin
    # │   └── start.py
    # └── core
    #    └── withdraw.py
    # 当执行start.py时,出现交互窗口
    #
    #    ------- Luffy Bank ---------
    # 1.  账户信息
    # 2.  提现
    # 选择1 账户信息 显示luffy的当前账户余额和信用额度。
    # 选择2 提现 提现金额应小于等于信用额度,利息为5%,提现金额为用户自定义。
    
    import os
    import sys
    import json
    
    # 取出当前文件的父目录,
    print(__file__)
    BASE_DIR = os.path.abspath(__file__)
    print(BASE_DIR)
    BASE_DIR1 = os.path.dirname(BASE_DIR)
    print(BASE_DIR1)
    BASE_DIR2 = os.path.dirname(BASE_DIR1)
    print(BASE_DIR2)
    
    # 跨模块导入,绝对路径
    sys.path.append(BASE_DIR2)
    print(sys.path)
    
    # 取出json文件的绝对路径
    file_path1 = BASE_DIR2 + "\" + "account" + "\" + "luffy.json"
    file_path2 = BASE_DIR2 + "\" + "account" + "\" + "tesla.json"
    file_path3 = BASE_DIR2 + "\" + "account" + "\" + "account.json"
    
    
    
    msg = """
        ------- Luffy Bank ---------
        1.  账户信息
        2.  转账
        3.  提现
      """
    
    print(msg)
    price = 75000
    print(price)
    choice = int(input('>'))
    
    
    f = open(file_path3, 'r')
    data = json.load(f)
    f.close()
    
    if choice == 1:
    
        print('账户余额', data['account'])
        print('信用额度', data['credit'])
    
    elif choice == 2:
    
        # tesla.json 文件操作
        f = open(file_path2, 'r+')
        data = json.load(f)
        data += price
        f.seek(0)
        json.dump(data,f)
        f.close()
    
        fin_price = price *(1 + 5/100 )
        print('你购买了tesla,花费了', fin_price)
    
        # luffy.json 文件操作
        f = open(file_path1, 'r+')
        data = json.load(f)
        data -= price
        print('余额剩下', data)
        f.seek(0)
        json.dump(data, f)
        f.close()
    
    elif choice == 3:
        from core import withdraw
        withdraw.takeout()
    View Code
    # withdraw 文件
    def takeout():
        import os
        import json
        # 取出当前文件的父目录,
    
        print(__file__)
        BASE_DIR = os.path.abspath(__file__)
        print(BASE_DIR)
        BASE_DIR1 = os.path.dirname(BASE_DIR)
        print(BASE_DIR1)
        BASE_DIR2 = os.path.dirname(BASE_DIR1)
        print(BASE_DIR2)
    
        # 取出json文件的绝对路径
        file_path1 = BASE_DIR2 + "\" + "account" + "\" + "luffy.json"
        file_path2 = BASE_DIR2 + "\" + "account" + "\" + "tesla.json"
        file_path3 = BASE_DIR2 + "\" + "account" + "\" + "account.json"
    
        withdraw_price = input('请输入提现金额>')
        withdraw_price = int(withdraw_price)
    
        f = open(file_path3, 'r')
        data = json.load(f)
        f.close()
    
        if withdraw_price <= data['credit']:
            cost_price = withdraw_price * (1 + 5 / 100)
            print('取出了', withdraw_price)
            data['account'] -= cost_price
    
            # 写入账户余额json
            f = open(file_path3, 'w')
            json.dump(data, f)
            f.close()
    View Code

    16、登录装饰器

    import os
    import sys
    import json
    
    # 取出当前文件的父目录,
    print(__file__)
    BASE_DIR = os.path.abspath(__file__)
    print(BASE_DIR)
    BASE_DIR1 = os.path.dirname(BASE_DIR)
    print(BASE_DIR1)
    BASE_DIR2 = os.path.dirname(BASE_DIR1)
    print(BASE_DIR2)
    
    # 跨模块导入,绝对路径
    sys.path.append(BASE_DIR2)
    print(sys.path)
    
    # 取出json文件的绝对路径
    file_path1 = BASE_DIR2 + "\" + "account" + "\" + "luffy.json"
    file_path2 = BASE_DIR2 + "\" + "account" + "\" + "tesla.json"
    file_path3 = BASE_DIR2 + "\" + "account" + "\" + "account.json"
    
    user_status = False
    
    
    def login(fun):
        def inner(*args, **kwargs):  # 可变参数
            _username = "alex"
            _password = "123"
            global user_status
    
            if user_status == False:
                username = input("user:")
                password = input("pasword:")
                if username == _username and password == _password:
                    print("welcome login....")
                    user_status = True
                else:
                    print("wrong username or password!")
    
            if user_status == True:
                fun(*args, **kwargs)  # 可变参数
    
        return inner
    
    @login
    def transfer():
        # tesla.json 文件操作
        f = open(file_path2, 'r+')
        data = json.load(f)
        data += price
        f.seek(0)
        json.dump(data,f)
        f.close()
    
        fin_price = price *(1 + 5/100 )
        print('你购买了tesla,花费了', fin_price)
    
        # luffy.json 文件操作
        f = open(file_path1, 'r+')
        data = json.load(f)
        data -= price
        print('余额剩下', data)
        f.seek(0)
        json.dump(data, f)
        f.close()
    
    msg = """
        ------- Luffy Bank ---------
        1.  账户信息
        2.  转账
        3.  提现
      """
    
    print(msg)
    price = 75000
    print(price)
    choice = int(input('>'))
    
    
    
    if choice == 1:
    
        f = open(file_path3, 'r')
        data = json.load(f)
        f.close()
        print('账户余额', data['account'])
        print('信用额度', data['credit'])
    
    elif choice == 2:
    
        transfer()
    
    elif choice == 3:
        from core import withdraw
    
        withdraw.takeout()
    View Code
    user_status = False
    def login(fun):
        def inner(*args, **kwargs):  # 可变参数
            _username = "alex"
            _password = "123"
            global user_status
    
            if user_status == False:
                username = input("user:")
                password = input("pasword:")
                if username == _username and password == _password:
                    print("welcome login....")
                    user_status = True
                else:
                    print("wrong username or password!")
    
            if user_status == True:
                fun(*args, **kwargs)  # 可变参数
    
        return inner
    
    @login
    def takeout():
        import os
        import json
        # 取出当前文件的父目录,
    
        print(__file__)
        BASE_DIR = os.path.abspath(__file__)
        print(BASE_DIR)
        BASE_DIR1 = os.path.dirname(BASE_DIR)
        print(BASE_DIR1)
        BASE_DIR2 = os.path.dirname(BASE_DIR1)
        print(BASE_DIR2)
    
        # 取出json文件的绝对路径
        file_path1 = BASE_DIR2 + "\" + "account" + "\" + "luffy.json"
        file_path2 = BASE_DIR2 + "\" + "account" + "\" + "tesla.json"
        file_path3 = BASE_DIR2 + "\" + "account" + "\" + "account.json"
    
        withdraw_price = input('请输入提现金额>')
        withdraw_price = int(withdraw_price)
    
        f = open(file_path3, 'r')
        data = json.load(f)
        f.close()
    
        if withdraw_price <= data['credit']:
            cost_price = withdraw_price * (1 + 5 / 100)
            print('取出了', withdraw_price)
            data['account'] -= cost_price
    
            # 写入账户余额json
            f = open(file_path3, 'w')
            json.dump(data, f)
            f.close()
    View Code

     

    17、日志

    import os
    import sys
    import json
    
    
    
    
    # 取出当前文件的父目录,
    print(__file__)
    BASE_DIR = os.path.abspath(__file__)
    print(BASE_DIR)
    BASE_DIR1 = os.path.dirname(BASE_DIR)
    print(BASE_DIR1)
    BASE_DIR2 = os.path.dirname(BASE_DIR1)
    print(BASE_DIR2)
    
    # 跨模块导入,绝对路径
    sys.path.append(BASE_DIR2)
    print(sys.path)
    
    # 取出json文件的绝对路径
    file_path1 = BASE_DIR2 + "\" + "account" + "\" + "luffy.json"
    file_path2 = BASE_DIR2 + "\" + "account" + "\" + "tesla.json"
    file_path3 = BASE_DIR2 + "\" + "account" + "\" + "account.json"
    file_path4 = BASE_DIR2 + "\" + "logs" + "\" + "bank.log"
    
    # 日志
    import logging
    logger = logging.getLogger('web')
    logger.setLevel(logging.DEBUG)
    
    file_log = logging.FileHandler(file_path4)
    logger.addHandler(file_log)
    file_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file_log.setFormatter(file_formatter)
    
    
    
    user_status = False
    
    def login(fun):
        def inner(*args, **kwargs):  # 可变参数
            _username = "alex"
            _password = "123"
            global user_status
    
            if user_status == False:
                username = input("user:")
                password = input("pasword:")
                if username == _username and password == _password:
                    print("welcome login....")
                    user_status = True
                else:
                    print("wrong username or password!")
    
            if user_status == True:
                fun(*args, **kwargs)  # 可变参数
    
        return inner
    
    @login
    def transfer():
        # tesla.json 文件操作
        f = open(file_path2, 'r+')
        data = json.load(f)
        data += price
        f.seek(0)
        json.dump(data,f)
        f.close()
    
        fin_price = price *(1 + 5/100 )
        print('你购买了tesla,花费了', fin_price)
    
        # luffy.json 文件操作
        f = open(file_path1, 'r+')
        data = json.load(f)
        data -= price
        print('余额剩下', data)
        f.seek(0)
        json.dump(data, f)
        f.close()
    
    msg = """
        ------- Luffy Bank ---------
        1.  账户信息
        2.  转账
        3.  提现
      """
    
    print(msg)
    logger.debug('start ... ')
    logger.debug('print menu')
    price = 75000
    print(price)
    choice = int(input('>'))
    logger.debug('enter choice')
    
    
    if choice == 1:
        logger.debug('select account ')
        f = open(file_path3, 'r')
        data = json.load(f)
        f.close()
        print('账户余额', data['account'])
        print('信用额度', data['credit'])
    
    elif choice == 2:
        logger.debug('transform bill ')
        transfer()
    
    elif choice == 3:
        from core import withdraw
    
        logger.debug('withdraw bill ')
        withdraw.takeout()
    View Code
  • 相关阅读:
    -bash: fork: Cannot allocate memory 问题的处理
    Docker top 命令
    docker常见问题修复方法
    The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
    What's the difference between encoding and charset?
    hexcode of é î Latin-1 Supplement
    炉石Advanced rulebook
    炉石bug反馈
    Sidecar pattern
    SQL JOIN
  • 原文地址:https://www.cnblogs.com/venicid/p/8464560.html
Copyright © 2011-2022 走看看