flask add_url_rule的使用

from flask import Flask,url_for
#url_for 接受两个参数(endpoint,**value)endpoint没有指定就是默认的函数名,根据 view_func.__name__
app
= Flask(__name__) @app.route('/') def hello_world(): return "Hello World!" #url注册的另一种方式 def my_list(): return '我是列表页' app.add_url_rule('/list/',endpoint='my_list',view_func=my_list) # 这里endpoint可以不填 ,view_func 一定要是函数名:具体看下面源码解释 #请求上下文 with app.test_request_context(): pass if __name__ == '__main__': app.run(debug=True)

route的源码分析,解释url_for 和 add_url_rule的使用

def route(self, rule, **options):
#先看下,route有几个参数,三个参数,对象,就是
app = Flask(__name__),rule 就是你注册的url '/',
**options可变长参数,能接受(字典,关键字参数:endpoint='index')
"""A decorator that is used to register a view function for a given URL rule. This does the same thing as :meth:`add_url_rule` but is intended for decorator usage:: @app.route('/') def index(): return 'Hello World' For more information refer to :ref:`url-route-registrations`. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ 

def decorator(f):
  #f = 相当于你装饰的函数内存对象:hello_world
  endpoint
= options.pop('endpoint', None) #options就是字典对象,用pop方法,如果你route()没有传递endpoint,就是None
  self.add_url_rule(rule, endpoint, f,
**options) #主要是调用这个方法装饰器还是执行了app.add_url_rule,把‘/’,None,hello_world 传来进去

  return f

return decorator

看下 add_url_rule干了什么事

    def add_url_rule(self, rule, endpoint=None, view_func=None,
                     provide_automatic_options=None, **options):
    #rule='/',endpoint = None ,view_func = hello_world
"""Connects a URL rule. Works exactly like the :meth:`route` decorator. If a view_func is provided it will be registered with the endpoint. Basically this example:: @app.route('/') def index(): pass Is equivalent to the following:: def index(): pass app.add_url_rule('/', 'index', index) If the view_func is not provided you will need to connect the endpoint to a view function like so:: app.view_functions['index'] = index Internally :meth:`route` invokes :meth:`add_url_rule` so if you want to customize the behavior via subclassing you only need to change this method. For more information refer to :ref:`url-route-registrations`. .. versionchanged:: 0.2 `view_func` parameter added. .. versionchanged:: 0.6 ``OPTIONS`` is added automatically as method. :param rule: the URL rule as string :param endpoint: the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint :param view_func: the function to call when serving a request to the provided endpoint :param provide_automatic_options: controls whether the ``OPTIONS`` method should be added automatically. This can also be controlled by setting the ``view_func.provide_automatic_options = False`` before adding the rule. :param options: the options to be forwarded to the underlying :class:`~werkzeug.routing.Rule` object. A change to Werkzeug is handling of method options. methods is a list of methods this rule should be limited to (``GET``, ``POST`` etc.). By default a rule just listens for ``GET`` (and implicitly ``HEAD``). Starting with Flask 0.6, ``OPTIONS`` is implicitly added and handled by the standard request handling. """ if endpoint is None: endpoint = _endpoint_from_view_func(view_func) #view_func = hello_world ,看下源码返回函数的名字 options['endpoint'] = endpoint methods = options.pop('methods', None) # if the methods are not given and the view_func object knows its # methods we can use that instead. If neither exists, we go with # a tuple of only ``GET`` as default. 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: #view_func = hello_world old_func = self.view_functions.get(endpoint) #view_functions = {} 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 #把endpoint=hello_world 添加到 view_functions 字典中。防止重命名
原文地址:https://www.cnblogs.com/wuheng-123/p/9682622.html