The Three Day
函数基础-练习
#、写函数,,用户传入修改的文件名,与要修改的内容,执行函数,完成批了修改操作
# def modify_file(filename,old,new):
# import os
# with open(filename,'r',encoding='utf-8') as read_f,\
# open('.bak.swap','w',encoding='utf-8') as write_f:
# for line in read_f:
# if old in line:
# line=line.replace(old,new)
# write_f.write(line)
# os.remove(filename)
# os.rename('.bak.swap',filename)
#、写函数,计算传入字符串中【数字】、【字母】、【空格] 以及 【其他】的个数
# def check_str(msg):
# res={
# 'al_num':,
# 'spance_num':,
# 'digit_num':,
# 'others_num':,
# }
#
# for s in msg:
# if s.isdigit():
# res['al_num']+=
# elif s.isspace():
# res['spance_num']+=
# elif s.isalpha():
# res['digit_num']+=
# else:
# res['others_num']+=
# return res
# res=check_str('hello name:aSB passowrd:alex3714')
# print(res)
#.判断用户传入的对象(字符串、列表、元组)长度是否大于5。
# def funcl(s,li,tup):
# s=len(s)
# i=len(li)
# o=len(tup)
# if s>:
# print('yes')
# else:
# print('no')
# if i>:
# print('yes')
# else:
# print('no')
# if o>:
# print('yes')
# else:
# print('no')
# return(s,i,o)
# m=funcl('fdsfwefewwe',(,,),[,,])
# print(m)
#.检查传入列表的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者 # def funcl(seq):
# if len(seq)>:
# seq=seq[:]
# return sequh
# print(funcl([,,,])) #.检查获取传入列表或元组对象的所有奇数位索引对应的元素,并将其作为新列表返回给调用者
# def func1(seq):
# return seq[::]
# print(func1([,,,,,]))
#
# def func2(dic):
# d={}
# for k,v in dic.items():
# if len(v)>:
# d[k]=v[:]
# return d
# print(func2({'k1':'werwerewr','k2':[,,,],'k3':('a','b','c')}))
# 、写函数,检查字典的每一个value的长度,如果大于2,那么仅保留前两个长度的内容,并将新内容返回给调用者。
# dic = {"k1": "v1v1", "k2": [,,,]}
# PS:字典中的value只能是字符串或列表
# def func3(dic):
# d={}
# for k,v in dic.items():
# if len(v) > :
# d[k]=v[:]
# return d
# print(func3({'k1':'abcdef','k2':[,,,],'k3':('a','b','c')}))
装饰器-练习
四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录 六:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果 七:为题目五编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中 扩展功能:用户可以选择缓存介质/缓存引擎,针对不同的url,缓存到不同的文件中 八:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作 九 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')
#题目四:
db='db.txt'
login_status={'user':None,'status':False}
def auth(auth_type='file'):
def auth2(func):
def wrapper(*args,**kwargs):
if login_status['user'] and login_status['status']:
return func(*args,**kwargs)
if auth_type == 'file':
with open(db,encoding='utf-8') as f:
dic=eval(f.read())
name=input('username: ').strip()
password=input('password: ').strip()
if name in dic and password == dic[name]:
login_status['user']=name
login_status['status']=True
res=func(*args,**kwargs)
return res
else:
print('username or password error')
elif auth_type == 'sql':
pass
else:
pass
return wrapper
return auth2 @auth()
def index():
print('index') @auth(auth_type='file')
def home(name):
print('welcome %s to home' %name) # index()
# home('egon') #题目五
import time,random
user={'user':None,'login_time':None,'timeout':0.000003,} def timmer(func):
def wrapper(*args,**kwargs):
s1=time.time()
res=func(*args,**kwargs)
s2=time.time()
print('%s' %(s2-s1))
return res
return wrapper def auth(func):
def wrapper(*args,**kwargs):
if user['user']:
timeout=time.time()-user['login_time']
if timeout < user['timeout']:
return func(*args,**kwargs)
name=input('name>>: ').strip()
password=input('password>>: ').strip()
if name == 'egon' and password == '123':
user['user']=name
user['login_time']=time.time()
res=func(*args,**kwargs)
return res
return wrapper @auth
def index():
time.sleep(random.randrange(3))
print('welcome to index') @auth
def home(name):
time.sleep(random.randrange(3))
print('welcome %s to home ' %name) index()
home('egon') #题目六:略
#题目七:简单版本
import requests
import os
cache_file='cache.txt'
def make_cache(func):
def wrapper(*args,**kwargs):
if not os.path.exists(cache_file):
with open(cache_file,'w'):pass if os.path.getsize(cache_file):
with open(cache_file,'r',encoding='utf-8') as f:
res=f.read()
else:
res=func(*args,**kwargs)
with open(cache_file,'w',encoding='utf-8') as f:
f.write(res)
return res
return wrapper @make_cache
def get(url):
return requests.get(url).text # res=get('https://www.python.org') # print(res) #题目七:扩展版本
import requests,os,hashlib
engine_settings={
'file':{'dirname':'./db'},
'mysql':{
'host':'127.0.0.1',
'port':3306,
'user':'root',
'password':'123'},
'redis':{
'host':'127.0.0.1',
'port':6379,
'user':'root',
'password':'123'},
} def make_cache(engine='file'):
if engine not in engine_settings:
raise TypeError('egine not valid')
def deco(func):
def wrapper(url):
if engine == 'file':
m=hashlib.md5(url.encode('utf-8'))
cache_filename=m.hexdigest()
cache_filepath=r'%s/%s' %(engine_settings['file']['dirname'],cache_filename) if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
return open(cache_filepath,encoding='utf-8').read() res=func(url)
with open(cache_filepath,'w',encoding='utf-8') as f:
f.write(res)
return res
elif engine == 'mysql':
pass
elif engine == 'redis':
pass
else:
pass return wrapper
return deco @make_cache(engine='file')
def get(url):
return requests.get(url).text # print(get('https://www.python.org'))
print(get('https://www.baidu.com')) #题目八
route_dic={} def make_route(name):
def deco(func):
route_dic[name]=func
return deco
@make_route('select')
def func1():
print('select') @make_route('insert')
def func2():
print('insert') @make_route('update')
def func3():
print('update') @make_route('delete')
def func4():
print('delete') print(route_dic) #题目九
import time
import os def logger(logfile):
def deco(func):
if not os.path.exists(logfile):
with open(logfile,'w'):pass def wrapper(*args,**kwargs):
res=func(*args,**kwargs)
with open(logfile,'a',encoding='utf-8') as f:
f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__))
return res
return wrapper
return deco @logger(logfile='aaaaaaaaaaaaaaaaaaaaa.log')
def index():
print('index') index()
随机推荐
- Sublime Text 报“Pylinter could not automatically determined the path to lint.py
Pylinter could not automatically determined the path to lint.py. please provide one in the settings ...
- 51Nod 1099 任务执行顺序 (贪心)
#include <iostream> #include <algorithm> using namespace std; +; struct node{ int r, q; ...
- ERROR: Could not connect to lockdownd, error code -19 -20
执行命令行 brew install libimobiledevice --HEAD
- 旧版本linaro-ubuntu更改软件源
最近打算研究下arm版本的linaro ubuntu桌面系统,但是在安装软件时速度实在太慢,便想修改一下软件源. 无奈查看系统版本时,显示的是linaro 11.12,但却不知和ubuntu有和关系, ...
- Java内置锁和简单用法
一.简单的锁知识 关于内置锁 Java具有通过synchronized关键字实现的内置锁,内置锁获得锁和释放锁是隐式的,进入synchronized修饰的代码就获得锁,走出相应的代码就释放锁. jav ...
- 114 Flatten Binary Tree to Linked List 二叉树转换链表
给定一个二叉树,使用原地算法将它 “压扁” 成链表.示例:给出: 1 / \ 2 5 / \ \ 3 4 6压扁后变成如下: ...
- ubuntu 文件解压命令
[解压.zip文件] unzip ./FileName.zip //前提是安装了unzip 安装unzip命令:sudo apt-get install unzip 卸载unzip软件 命令:sudo ...
- 用vue.js重构订单计算页面
在很久很久以前做过一个很糟糕的订单结算页面,虽然里面各区域(收货地址)使用模块化加载,但是偶尔会遇到某个模块加载失败的问题导致订单提交的数据有误. 大致问题如下: 1. 每个模块都采用usercont ...
- Java基础教程(25)--I/O
一.I/O流 I/O流表示输入源或输出目标.流可以表示许多不同类型的源和目标,例如磁盘文件.设备.其他程序等. 流支持许多不同类型的数据,包括字节.原始数据类型.字符和对象等.有些流只传递数据 ...
- Vivado增量式编译
Vivado 中的增量设计会重新利用已有的布局布线数据来缩短运行时间,并生成可预测的结果.当设计有 95% 以上的相似度时,增量布局布线的运行时间会比一般布局布线平均缩短2倍.若相似度低于80%,则使 ...