1. 程式人生 > 實用技巧 >四、新增路由的兩種方式

四、新增路由的兩種方式

在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。