from flask import Flask,views,url_for app = Flask(__name__) class IndexView(views.View): def dispatch_request(self): #必须实现
print(url_for('index')) return 'hello world' app.add_url_rule('/',endpoint='index',view_func=IndexView.as_view('index')) if __name__ == '__main__': app.run(debug=True)
#上面的类方法看起来并没有函数好用,那为什么还要用它。
#比如说有几个直传json数据的api class JSONView(views.View): def get_data(self): raise NotImplementedError def dispatch_request(self): return jsonify(self.get_data()) class ListView(JSONView): def get_data(self): return {"username":"xiaowu","password":"123456"} app.add_url_rule('/list/',endpoint='list',view_func=ListView.as_view('list'))
#几个api要传递统一的变量 class UNIFYView(views.View): def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.content = {"abs":"今年过年不收礼,收礼只收女票"} class LoginView(UNIFYView): def dispatch_request(self): self.content.update( username = "xiaowu", password = "123456" ) return render_template('login.html',**self.content) app.add_url_rule('/login/',endpoint='login',view_func=LoginView.as_view('login')) class RegisterView(UNIFYView): def dispatch_request(self): return render_template('login.html', **self.content) app.add_url_rule('/register/', endpoint='register', view_func=LoginView.as_view('register'))