1.演示之前需要先写一个装饰器
# 装饰器 def wrapper(func): def inner(*args, **kwargs): print('操作函数%s之前' % func.__name__) ret = func(*args, **kwargs) print('操作函数%s之后' % func.__name__) return func.__name__ return inner
2.写一个CBV的例子
# 导入模块 from flask import Flask, views, url_for app = Flask(__name__)
# 首页视图函数 @app.route("/") def index(): return "this is index page !"
# 登录视图类,继承MethodView class Login(views.MethodView): # 允许访问方式 methods = ["GET", "POST"] # 路由装饰器,如有多个,列表方式展示 # 顺序:列表从头到尾,装饰由内向外,一一对应 decorators = [wrapper, ] # 处理GET请求 def get(self): print(url_for("my_login")) return 'this is login page !' # 处理POST请求 def post(self): return "Successful!"
# 文章视图类,继承MethodView class Articles(views.MethodView): methods = ["GET", "POST"] decorators = [wrapper, ] # 处理文章GET请求 def get(self): print(url_for('articles')) return 'this is articles list !' # 处理文章POST请求 def post(self): return "Add Successful !"
# 登录页面 app.add_url_rule("/login", endpoint=None, view_func=Login.as_view("my_login")) # 文章页面 app.add_url_rule("/articles", endpoint=None, view_func=Articles.as_view("articles"))
if __name__ == '__main__': app.run('127.0.0.1', 5005, debug=True)