1.试图
# coding=utf-8
from flask import Flask, views
from functools import wraps
app = Flask(__name__)
app.config.from_object("settings.DevelopmentConfig")
# 直接使用装饰器是FBC
def wapper(func):
@wapper(func)
def inner(*arg,**kwargs):
print("before")
return func(*arg, **kwargs)
return inner
@app.route("/index", methods=["POST", "GET"])
@wapper # 装饰器需要写到route装饰器的下面
def index():
pass
# 下面通过类给请求加上装饰器是CBV
class IndexView(views.View):
methods = ['GET']
decorators = [wapper, ]
def dispatch_request(self):
print('Index')
return 'Index!'
app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
class IndexView(views.MethodView):
methods = ['GET']
decorators = [wapper, ] # 给所有的请求加装饰器
def get(self):
return 'Index.GET'
def post(self):
return 'Index.POST'
app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint
if __name__ == '__main__':
app.run()