给类添加装饰器有多种方法:
1.可以在类中的某个方法上边直接@添加,这个粒度细.无需详细介绍
2.也可以在类中通过 decorators=[, ]的形式添加,这样的话,类中的所有方法都会被一次性加上装饰器,粒度粗:
列表中多个装饰器的话,装饰器的添加顺序:
列表中: 从前 -> 往后,对应:
函数上边: 从下 -> 到上
下边以一个简单的flask项目为例演示一遍
# app.py内容 import time from flask import Flask, views from flask import render_template, redirect, request app = Flask(__name__) # 装饰器1 def print_time(func): def inner(*args, **kwargs): st = time.time() ret = func(*args, **kwargs) et = time.time() print("use time: {}".format(et - st)) return ret return inner # 装饰器2 def say_hi(func): def inner(*args, **kwargs): print("第二层装饰器开始") ret1 = func(*args, **kwargs) et = time.time() print("第二层装饰器结束") return ret1 return inner class Login(views.MethodView): # decorators = [print_time, say_hi] # 顺序相当于: # @say_hi # @print_time # 结果: # 第二层装饰器开始 # use time: 0.005026817321777344 # 第二层装饰器结束 decorators = [say_hi, print_time] # 顺序相当于: # @print_time # @say_hi # 结果: # 第二层装饰器开始 # 第二层装饰器结束 # use time: 0.006980419158935547 def get(self, *args, **kwargs): return render_template("login.html") def post(self, *args, **kwargs): print( request.files) # ImmutableMultiDict([('myFile', <FileStorage: 'vim常用命令总结.md' ('application/octet-stream')>)]) print(request.files.get("myFile")) # < FileStorage: 'vim常用命令总结.md' ('application/octet-stream')> my_file = request.files.get("myFile") my_file.save(my_file.filename) return "123" app.add_url_rule("/login", view_func=Login.as_view(name="login")) if __name__ == '__main__': app.run()
<!-- templates/login.html中内容 --> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <input type="text" name="username"> <input type="file" name="myFile"> <input type="submit" value="提交"> </form> </body> </html>