在Flask中,添加路由有两种方式:(一般情况下都是用第一种方式)
第一种:常见的装饰器模式
@app.route("/") def index(): return "Hello World"
通过这种方式,将rule与视图函数对应起来
第二种:通过阅读装饰器模式添加路由的源码发现
def route(self, rule, **options): """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): endpoint = options.pop("endpoint", None) self.add_url_rule(rule, endpoint, f, **options) return f return decorator
是通过self.add_url_rule这个方式建立起rule与视图函数的对应关系的,所以可以这样添加,
def home(): return "Hello, home!" app.add_url_rule("/home", endpoint=None, view_func=home)
endpoint:给rule起一个别名,相当于django path路由函数中的name。