Class view flask-
- Standard Class View
-
1 from flask import Flask, render_template, views, jsonify 2 3 app = Flask(__name__) 4 5 6 class JsonView(views.View): 7 def get_response(self): 8 raise NotImplementedError() 9 10 def dispatch_request(self): 11 response = self.get_response() 12 return jsonify(response) 13 14 15 class IndexView(JsonView): 16 def get_response(self): 17 context = { 18 'username': 'ivy' 19 } 20 return context 21 22 23 app.add_url_rule('/', view_func=IndexView.as_view('index')) 24 25 26 class FakeView(object): 27 def __init__(self): 28 super().__init__() 29 self.context = { 30 'username': 'ivy', 31 } 32 33 34 class TestView(JsonView, FakeView): 35 def get_response(self): 36 self.context.update({'age': 23}) 37 return self.context 38 39 40 app.add_url_rule('/test', view_func=TestView.as_view('test')) 41 42 if __name__ == '__main__': 43 app.run()
View.View standard class inherits from view must flask and custom implementations dispatch_request method for routing in the last used add_url_rule app, the first parameter is a view corresponding to that route, view_func the route corresponding to the development view, the view class using the class the method as as_view view corresponding to the view function.
- Class View can be achieved using the abstract view, but let subclasses view custom implementation returns rules for some common attribute can be used multiple inheritance way to obtain.
-
- The class-based scheduling view
-
1 from flask import Flask, render_template, views, jsonify 2 3 app = Flask(__name__) 4 5 6 class LoginView(views.MethodView): 7 def get(self): 8 return 'get' 9 10 def post(self): 11 return 'post' 12 13 14 app.add_url_rule('/login', view_func=LoginView.as_view('login')) 15 16 if __name__ == '__main__': 17 app.run()
MethodView can be called from class method function definition view based on their own request method, as with the View class django
-
- Class view decorator
-
1 from flask import Flask, views, request 2 from functools import wraps 3 4 app = Flask(__name__) 5 6 7 def login_required(func): 8 @wraps(func) 9 def wrapper(*args, **kwargs): 10 # 模拟登陆验证 11 name = request.args.get('name') 12 if name: 13 return func(*args, **kwargs) 14 return '未登录' 15 16 return wrapper 17 18 19 @app.route('/') 20 @login_required 21 def index(): 22 return 'index page' 23 24 25 class IndexView(views.View): 26 decorators = [login_required] 27 28 def dispatch_request(self): 29 return 'index page view' 30 31 32 app.add_url_rule('/index', view_func=IndexView.as_view('index_view')) 33 34 if __name__ == '__main__': 35 app.run()
Class View function and wants to use the same view of the decorator, direct use of the class attribute decorators, decorators is a list of the function body to accept the decorator
-