Flask的路由系统
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = ‘Wu‘ from flask import Flask app = Flask(__name__) # @app.route(‘/index‘) def index(): return ‘Index‘ def login(): return ‘Login‘ app.add_url_rule(‘/index‘, ‘index‘, index, methods=[‘GET‘]) app.add_url_rule(‘/login‘, ‘login‘, login, methods=[‘GET‘]) if __name__ == ‘__main__‘: app.run()
源码实现:
def _endpoint_from_view_func(view_func): assert view_func is not None, ‘expected view func if endpoint ‘ ‘is not provided.‘ return view_func.__name__ # endpoint等于视图函数的名字 def add_url_rule(self, rule, endpoint=None, view_func=None, **options): if endpoint is None: # 2. 如果endpoint为None endpoint = _endpoint_from_view_func(view_func) # 3. endpoint等于。。。 options[‘endpoint‘] = endpoint methods = options.pop(‘methods‘, None) def route(self, rule, **options): def decorator(f): endpoint = options.pop(‘endpoint‘, None) # 1.如果不设置endpoint则为None self.add_url_rule(rule, endpoint, f, **options) # flask路由的本质就是调用self.add_url_rule return f return decorator
CBV
Django中处理请求的方式有FBV和CBV两中,其实Flask中也支持CBV,它的CBV和Django的类似。