添加路由
app.route()添加路由分析
from flask import Flask
app = Flask(__name__)
app.debug = True
# 先执行route()函数,
'''
1.第一步 返回闭包函数decorator
    def route(self, rule, **options):
        # self = app
        # rule = '/'
        # options = {methods:["GET", "POST"],endpoint:"index"}
        def decorator(f):
            endpoint = options.pop('endpoint', None)
            #将路由关系添加到app对象中
            self.add_url_rule(rule, endpoint, f, **options)
            return f
        return decorator
2.第二步 装饰login函数(@decorator)即index=decorator(index)
'''
@app.route("/", methods=["GET", "POST"], endpoint="index")
def login():
    return "hello"
def login():
    return "login"
# 路由添加方式等价于
app.add_url_rule("/login", "login", login, methods=["GET", "POST"])
if __name__ == '__main__':
    app.run()
 
 app.add_url_rule分析 
    def add_url_rule(self, rule, endpoint=None, view_func=None,
                     provide_automatic_options=None, **options):
        # 如果未指定endpoint,默认调用_endpoint_from_view_func返回视图函数名字作为endpoint
        if endpoint is None:
            endpoint = _endpoint_from_view_func(view_func)
        options['endpoint'] = endpoint
        methods = options.pop('methods', None)
        if methods is None:
            methods = getattr(view_func, 'methods', None) or ('GET',)
        if isinstance(methods, string_types):
            raise TypeError('Allowed methods have to be iterables of strings, '
                            'for example: @app.route(..., methods=["POST"])')
        methods = set(item.upper() for item in methods)
        # Methods that should always be added
        required_methods = set(getattr(view_func, 'required_methods', ()))
        # starting with Flask 0.8 the view_func object can disable and
        # force-enable the automatic options handling.
        if provide_automatic_options is None:
            provide_automatic_options = getattr(view_func,
                'provide_automatic_options', None)
        if provide_automatic_options is None:
            if 'OPTIONS' not in methods:
                provide_automatic_options = True
                required_methods.add('OPTIONS')
            else:
                provide_automatic_options = False
        # Add the required methods now.
        methods |= required_methods
        rule = self.url_rule_class(rule, methods=methods, **options)
        rule.provide_automatic_options = provide_automatic_options
        self.url_map.add(rule)
        if view_func is not None:
            old_func = self.view_functions.get(endpoint)
            if old_func is not None and old_func != view_func:
                raise AssertionError('View function mapping is overwriting an '
                                     'existing endpoint function: %s' % endpoint)
            self.view_functions[endpoint] = view_func
 
路由模式之CBV