第四章练习题

老子叫甜甜 提交于 2020-11-30 23:26:58

1、logging模块有几个日志级别?

debug

info

warning

error

critical

 

2、请配置logging模块,使其在屏幕和文件里同时打印以下格式的日志

2017-10-18 15:56:26,613 - access - ERROR - account [1234] too many login attempts
 1 import logging
 2 
 3 logger = logging.getLogger('access')
 4 logger.setLevel(logging.ERROR)
 5 
 6 
 7 
 8 ch = logging.StreamHandler()
 9 fh = logging.FileHandler('homework-logging')
10 
11 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s' )
12 ch.setFormatter(formatter)
13 fh.setFormatter(formatter)
14 
15 logger.addHandler(ch)
16 logger.addHandler(fh)
17 
18 
19 logger.error('account [1234] too many login attempts')
View Code

 

3、json、pickle、shelve三个区别是什么?

json  pickle shelve都是序列号,将内存里的数据类型变成字符串,或者从文件里反序列化,变成他原有的格式。

json是夸平台的, 只支持 str, int list, dict,tuple 这几种数据类型
pickle和json用法相同,支持全部数据类型,但只能在python里使用
shelve和pickle一样,支持所有数据类型,只能在python里使用,可以多次dump和local 还可以进行修改

 

4、json的作用是什么

json 用于跨平台之间的数据传输,数据传输时只能用字符串,利用json可以对内容里的数据转换成字符串或者从字符串转换成原来本有的数据类型

 

5、subprocess执行命令方法有几种?

subprocess.run(['df','-h'])

a = subprocess.call(['df','-h'])

 

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)

i、打印的内容是什么:

/usr/local/nginx/

ii、os.path.dirname和os.path.abspath含义是什么?

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 = true
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'

i、修改时区 default-time-zone = '+8:00' 为 校准的全球时间 +00:00

import configparser

conf =configparser.ConfigParser()
conf.read('conf.ini')


conf['mysqld']['default-time-zone'] = '+00:00'


conf.write(open('conf.ini','w'))
View Code

ii、删除 explicit_defaults_for_timestamp = true

import configparser

conf =configparser.ConfigParser()
conf.read('conf.ini')



conf.remove_option('mysqld','explicit_defaults_for_timestamp')

conf.write(open('conf.ini','w'))
View Code

iii、为DEFAULT增加一条 character-set-server = utf8

import configparser

conf =configparser.ConfigParser()
conf.read('conf.ini')

conf['DEFAULT']['character-set-server'] = 'utf8'


conf.write(open('conf.ini','w'))
View Code

 10、写一个6位随机验证码程序(使用random模块),要求验证码中至少包含一个数字、一个小写字母、一个大写字母.

 

 

 

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

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>luffycity.com</title>
</head>
<body>
</body>
</html>
import re

f = open('index.html','r',encoding='utf-8')
data = f.read()


a = re.findall('luffycity.com',data)
print(a)
View Code

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,并且锁定账号。
    import json,time
    f = open('account.json','r')
    data = json.load(f)
    d = time.strftime('%Y-%m-%d')
    
    
    
    
    
    username = '1234.json'
    password = 'password'
    
    count = 0
    
    while count <3:
    
        if data['status'] == 1:
            print('用户被锁定')
            break
        elif d > data['expire_date']:
            print('账号已过期')
            break
        else:
            _usernam = input('username:').strip()
            _password = input('password').strip()
    
            if _usernam == username and _password == password:
                print('登陆成功%s' %_usernam)
                break
    
            else:
                print('wrong password')
            count += 1
    
    
    else:
        data['status'] = 1
        json.dump(data,open('account.json','w'))
    View Code

13、

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

需求如下: 

目录结构为

.
├── account
│   ├── luffy.json
│   └── tesla.json
└── bin
      └── start.py

 

15、

16、

17、

的答案一起

 1 import os,sys
 2 import json
 3 import logging
 4 core_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 5 
 6 sys.path.append(core_path)
 7 from core import  withdraw
 8 
 9 
10 
11 _username = 'alex'
12 _password = 'abc123'
13 flag_logger = False
14 
15 msg = """
16 1. 账户信息
17 2.转账
18 3.提现
19 """
20 json_path = os.path.join(core_path,'account')
21 
22 
23 logging.basicConfig(filename=os.path.join(core_path,'logs/bank.log'),level='DEBUG',
24                     format='%(asctime)s-%(message)s',
25                     )
26 
27 
28 def loggin(func):
29     def inner():
30         global flag_logger
31         if not flag_logger:
32             username = input('username:').strip()
33             password = input('password').strip()
34             if username == _username and password == _password:
35                 print('登陆成功,欢迎回来%s'%username)
36                 logging.debug('登陆成功')
37                 flag_logger = True
38             else:
39                 print('密码错误')
40 
41         if flag_logger == True:
42             func()
43     return inner
44 
45 
46 
47 @loggin
48 def print_info():
49     luffy_data = json.load(open(os.path.join(json_path,'luffy.json'),'r'))
50     print('account_balance:',luffy_data['account_balance'])
51     print('credit_account:',luffy_data['credit_account'])
52     logging.warning('查询账户')
53 
54 @loggin
55 def transfer_account():
56     luffy_data = json.load(open(os.path.join(json_path,'luffy.json'),'r'))
57     tesla_data = {'account_balance':750000}
58     luffy_data['account_balance'] = luffy_data['account_balance']-tesla_data['account_balance']*(1+0.05)
59     json.dump(luffy_data,open(os.path.join(json_path,'luffy.json'),'w',encoding='utf-8'))
60     json.dump(tesla_data,open(os.path.join(json_path,'tesla.json'),'w',encoding='utf-8'))
61     print('转账成功!,账上余额:%s'%luffy_data['account_balance'])
62     logging.error('转账成功')
63 
64 @loggin
65 def extract_account():
66     money = input('moneys>>>')
67     if money.isdigit():
68         money = int(money)
69         withdraw.withdraws_func(money, json_path,logging)
70 
71 
72 
73 
74 
75 
76 def main():
77     while True:
78         print('luffy Bank'.center(30,'-'))
79         print(msg)
80         choice = input('>>>').strip()
81         if not choice:
82             continue
83 
84         elif choice == '1':
85             print_info()
86         elif choice == '2':
87             transfer_account()
88         elif choice == '3':
89             extract_account()
90         elif choice == 'q':
91             exit()
92         else:
93             print('输入❌')
94 
95 
96 main()
strat
 1 import os,json
 2 def withdraws_func(money,json_path,logging):
 3     luffy_data = json.load(open(os.path.join(json_path,'luffy.json'),'r',encoding='utf-8'))
 4     if money <= luffy_data['credit_account']:
 5         luffy_data['credit_account'] = luffy_data['credit_account'] - money*(1+0.05)
 6         json.dump(luffy_data,open(os.path.join(json_path,'luffy.json'),'w',encoding='utf-8'))
 7         print('提现%s元成功'%money)
 8         logging.debug('提现成功')
 9     else:
10         print('\33[0;31m提现金额大于你的信用额度!\033[0m')
withdraw

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!