flask的CBV模式
def auth(func): def inner(*args, **kwargs): result = func(*args, **kwargs) return result return inner class IndexView(views.MethodView): # methods = [‘POST‘] #只允许POST请求访问 decorators = [auth,] #如果想给所有的get,post请求加装饰器,就可以这样来写,也可以单个指定 def get(self): #如果是get请求需要执行的代码 v = url_for(‘index‘) print(v) return "GET" def post(self): #如果是post请求执行的代码 return "POST" app.add_url_rule(‘/index‘, view_func=IndexView.as_view(name=‘index‘)) #name指定的是别名,会当做endpoint使用 if __name__ == ‘__main__‘: app.run()
flask中的FBV模式
方式一: @app.route(‘/index‘,endpoint=‘xx‘) def index(nid): url_for(‘xx‘,nid=123) return "Index" 方式二: def index(nid): url_for(‘xx‘,nid=123) return "Index" app.add_url_rule(‘/index‘,index)
随便练习的CBV和FBV
from flask import Flask,render_template,redirect,views app = Flask(__name__) import functools def wapper(func): @functools.wraps(func) def inner(*args,**kwargs): print(‘before‘) return func(*args,**kwargs) return inner @app.route(‘/xxxx‘,methods=[‘GET‘,‘POST‘]) @wapper def index(): return "Index" # 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=‘index1‘)) # 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=‘index2‘)) # name=endpoint if __name__ == ‘__main__‘: app.run()
原文地址:https://www.cnblogs.com/1996-11-01-614lb/p/8975371.html
时间: 2024-10-09 04:09:12