flask中添加路由的方式

发布时间 2023-06-26 11:36:13作者: 一先生94

在Flask中,添加路由有两种方式:(一般情况下都是用第一种方式)

方式一:常见的装饰器模式

@app.route("/")
def index():
    return "Hello World"

方式二:通过阅读装饰器模式添加路由的源码发现

 

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。

如何使用通过别名(endpoint)找到rule呢?(如果不起别名,就默认为函数名)

@app.route("/", endpoint="index")
def index():
    return "Hello World"


def home():
    from flask import url_for
    r = url_for("index")
    # /
    print(r)
    return "Hello, home!"