装饰器实例
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import time, random flag =True def timer(flag): def decorator(func): def wrapper(*args, **kwargs): if flag: start = time.time() ret = func(*args,**kwargs) end = time.time() print(end-start) return ret else: return func(*args, **kwargs) return wrapper return decorator db_file = "db.txt" login_status = {"user": None, "login_time": None, "time_out": 10} def auth(switch=True, auth_type="file"): """ #该装饰器用于用户登陆,用户登陆一次后,在超时时间内再次调用装饰器,无需再次登陆,否则需要重新登陆。 :param switch: #是否开启验证 bool :param auth_type: #验证方式,默认以读取文件匹配信息进行验证。 :return: """ def decorator(func): def wrapper(*args, **kwargs): if switch: if login_status["user"]: #如果用户登陆过则判断,是否已经超时 now_time = time.time() if (now_time - login_status['login_time']) < login_status["time_out"]: return func(*args,**kwargs) if auth_type == "file": #如果没用登陆过,或者已经超时,则需要重新登陆 user = input("请输入用户名:") pwd = input("请输入密码") with open(db_file, "r", encoding="utf-8") as f: for i in f: info = eval(i) if user == info["name"] and pwd == info["password"]: print("登陆成功!") success = time.time() login_status.update([("user",user),("login_time",success)]) #登陆成功则更新登陆时间 return func(*args,**kwargs) else: print("用户名密码错误!") elif auth_type == "sql": pass else: pass else: return func(*args, **kwargs) return wrapper return decorator @auth() @timer(flag) def index(): # time.sleep(random.randrange(3)) time.sleep(15) print("index_page!") @auth() @timer(flag) def home(): print("home_page!") index() home()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
import requests,os,time engine_setting ={ "file":{"datadir":"./db"}, "mysql":{ "host":"127.0.0.1", "username":"root", "password":"1q2w3e", "port":"3306", "database":"page_cache" }, "redis":{ "host": "127.0.0.1", "username": "root", "password": "1q2w3e", "port": "6379", } } def create_cache(cache_type = "file"): """ #用于装饰请求网页函数,第一次请求会建立缓存文件,后续在次访问该网址会读取缓存文件。 :param cache_type: #缓存类型 :return: """ def decorator(func): def wrapper(*args,**kwargs): if cache_type == "file": #设置用本地文件缓存 data_dir_path = engine_setting["file"]["datadir"] #缓存目录获取 if not os.path.exists(data_dir_path): os.mkdir(data_dir_path) #缓存目录如果不存在,建立目录 cache_file = "".join((data_dir_path, "/", args[0].split("/")[2], ".txt")) #缓存文件路径 if os.path.exists(cache_file) and os.path.getsize(cache_file): #如果缓存文件存在,则读取缓存返回给用户 with open(cache_file, "r", encoding="utf-8") as fr: # print("读缓存!") return fr.read() else: #否则直接访问url,将信息写入缓存文件,然后返回给用户 ret = func(*args,*kwargs) with open(cache_file , "w", encoding="utf-8") as fw: fw.write(ret) # print("创建缓存成功!") return ret elif cache_type == "redis": pass elif cache_type == "memcached": pass else: pass return wrapper return decorator flag = True def timer(flag): def wrapper(func): def decorator(*args,**kwargs): if flag: start = time.time() ret = func(*args,**kwargs) end = time.time() print(end - start) return ret else: return func(*args, **kwargs) return decorator return wrapper @timer(flag) @create_cache() def get_page(url): r = requests.get(url) return r.text print(get_page("http://www.baidu.com"))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
port time,os def time_format(type): if type == "logfile_time": return time.strftime("%Y-%m-%d-%H") elif type == "logging_time": return time.strftime("%Y-%m-%d %X") file_info = {"message":{"logfile_time": None, "file_name": None,"file_id":0}, "secure":{"logfile_time": None, "file_name": None,"file_id":0}} def logging(file_path,log_type="message"): def decorator(func): def wrapper(*args, **kwargs): # if file_info[log_type]["file_name"]: # print(os.path.getsize(file_info[log_type]["file_name"])) if not os.path.exists(file_path): #判断目录是否存在 os.mkdir(file_path) if file_info[log_type]["file_name"] and \ file_info[log_type]["logfile_time"] == time_format("logfile_time")\ and os.path.getsize(file_info[log_type]["file_name"]) < 100: #如果日志文件存在,且时间对的上现有写入文件时间,且文件小于100字节就继续在原文件写入 # print("还是上一个日志文件") ret = func(*args,**kwargs) with open(file_info[log_type]["file_name"], "a",encoding="utf-8") as f: f.write("{time} {func_n} run\n".format(time = time_format("logging_time"),func_n = func.__name__)) return ret else: ret = func(*args, **kwargs) file_info[log_type]["logfile_time"] = time_format("logfile_time") if file_info[log_type]["logfile_time"] != time_format("logfile_time"): #时间戳不一致,生成新日志文件 # print("根据时间切割了,生成了新文件") file_name = "".join((file_path, "/", log_type,"-", time_format("logfile_time"),".log")) file_info[log_type]["file_id"] = 0 elif not file_info[log_type]["file_name"]: #日志文件不存在,(刚运行程序),生成新日志文件 # print("第一次调用,会走这里") file_name = "".join((file_path, "/", log_type,"-", file_info[log_type]["logfile_time"],".log")) else: # print("根据文件大小切割,生成了新文件") #文件大于100字节,生成新文件,文件名为原有日志文件加小标号 file_info[log_type]["file_id"] += 1 file_name = "".join((file_path, "/", log_type,"-", file_info[log_type]["logfile_time"],"-",str(file_info[log_type]["file_id"]),".log")) file_info[log_type]["file_name"] = file_name #更新字典中日志的名字 with open(file_name, "w", encoding="utf-8") as f: f.write("{time} {func_n} run\n".format(time = time_format("logging_time"),func_n = func.__name__)) return ret return wrapper return decorator @logging("./log") def f1(): pass # print("f1,哈哈哈哈哈哈哈!") @logging("./log",log_type="secure") def f2(): pass # print("f2,哈哈哈吧哈哈") count = 0 while count < 300: time.sleep(1) f1() count+=1 # f2()