flask 的cbv
flask的cbv
from flask import Flask, views, url_for
app = Flask(__name__)
def wrapper(func):
def inner(*args, **kwargs):
print('你追我,你追到我,我就让你')
res = func(*args, **kwargs)
print('嘿嘿嘿')
return res
return inner
# 想用cbv必须先导入views
class Index(views.View):
methods = ['GET'] # 规定哪些请求方法可以请求我们这个路由
decorators = [wrapper,] # 给我们的响应添加装饰器
# 如果你继承的是views必须写这个dispatch_request响应方法
def dispatch_request(self):
return 'Hello,China'
# 再as_view(name的作用和endpoint一样都是起别名,但是如果有endpoint他的优先级会高于name)
# 注意:这里必须要给这个函数起别名,不然的话所有的函数请求的名字都是view会蹦的
app.add_url_rule('/index', view_func=Index.as_view(name='index'), endpoint='index1')
# views.MethodView可以实现不同的请求不同的方法get走get方法,post走post方法
# MethodView的本质就是重写了dispatch_request方法
class Login(views.MethodView):
methods = ['POST', 'GET']
def get(self):
print(url_for('index1'))
return 'get方法'
def post(self):
return 'post方法'
app.add_url_rule('/login', view_func=Login.as_view(name='login'))
if __name__ == '__main__':
app.run()
Only you can control your future
You're not alone. You still have family,peopel who care for you and want to save you.