First, the definition of decorator
Decorating it is a special closure function
def timer(func):
def inner(*args,**kwargs):
'''What to do before executing the function'''
re = func(*args,**kwargs)
'''What to do after executing the function' ''
return re
return inner
The principle of open and closed
1. is open to extension
Why open up to extensions?
We say that it is impossible for any program to have all the functions in mind at the beginning of the design and not make any updates and modifications in the future. So we have to allow the code to expand, add new functionality.
2. is closed to modification
Why is it closed for modification?
As we just mentioned, because a function we wrote is likely to be delivered to other people for use, if we modify it at this time, it is likely to affect other users who are already using the function.
Decorators follow this open-closed principle perfectly.
3. Decorator
1) Simple decorator
import time
def timmer(fucn):
def inner():
start_time=time.time()
fucn()
end_time=time.time()
print("run time is %s"%(end_time-start_time))
return inner
@timmer
def index():
time.sleep(3)
print("welcome to index")
3.1) Multiple decorators are loaded as a function
#Decorator access 3-6 function to detect whether the user is logged in, if not logged in, let the user log in
def auth(f1):
def inner(*args,**kwargs):
if user_status.get('status'):
res = f1(*args,**kwargs)
return res
else:
print("Please login first")
login()
res=f1(*args,**kwargs)
return res
return inner
# Decorator user login, write log
def user_log(fucn):
def inner(*args,**kwargs):
struct_time = time.localtime()
log_time = str(time.strftime("%Y-%m-%d %H:%M:%S", struct_time))
with open("user.log",mode='a',encoding="utf-8") as f_write:
f_write.write('User:%s time %s\n' % (user_status['username'], log_time))
res =fucn(*args,**kwargs)
return res
return inner
@auth
@user_log
def article():
print("welcome %s article page" %user_status["username"])