日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 综合教程 >内容正文

综合教程

四、添加路由的两种方式

發布時間:2024/8/26 综合教程 23 生活家
生活随笔 收集整理的這篇文章主要介紹了 四、添加路由的两种方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

如何使用通過別名(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!"

===================================================================================================================================

如何通過路由傳遞參數呢?<轉換器:參數名>

@app.route("/<int:uid>/", endpoint="index")
def index(uid):
    return "Hello {}".format(uid)

常用的轉換器:int、float、path、uuid、string、any、default

不難發現,沒有正則表達式的轉換器,那么我們可以自定義:

 1 class RegexConverter(BaseConverter):
 2     def __init__(self, map, regex):
 3         super(RegexConverter, self).__init__(map)
 4         # 為什么只用賦值regex就可以了呢?其他轉化器是在類屬性regex(正則表達式)的基礎上實現的
 5         self.regex = regex
 6 
 7     def to_python(self, value):
 8         """將提取后的值進行處理"""
 9         return value
10 
11     def to_url(self, value):
12         """用于反向解析url"""
13         val = super(RegexConverter, self).to_url(value)
14         return val
15 
16 
17 # 雖然我們已經定制好了正則轉換器類,但是應用程序不知道,我們還要通知一下
18 app.url_map.converters["regex"] = RegexConverter
19 
20 
21 @app.route('/<regex("d+"):uid>/', endpoint="index")
22 def index(uid):
23     return "Hello {}".format(uid)

如何rule里面通過路由傳參,那如何反向解析呢?

1 url_for(endpoint, **values)

參數通過**values傳遞:url_for(endpoint="index", uuid=10)

===================================================================================================================================

app.route方法常見的參數:

rule:URL規則

view_func:視圖函數的名稱

default:默認值,當URL中無參數,函數需要參數時,使用default={'k':'v'}為函數提供參數

endpoint:名稱,用于反向生產URL,即:url_for('名稱')

strict_slashes=None:對URL最后的/符號是否嚴格要求

redirect_to=None:重定向到指定地址

subdomain=None:子域名訪問

==================================================================================================================================

路由重點:url、methods、endpoint、int轉換器、url_for

==================================================================================================================================

如何給視圖函數添加裝飾器?

裝飾器要放在app.route的下面(放在上面,只會執行一次),并且必須要保留被裝飾函數的元信息,因為當我們使用一個裝飾器去裝飾多個函數時,不保留被裝飾函數的元信息,endpoint會默認為函數名,這樣就會都等于裝飾器函數內部被返回的函數名,導致endpoint重名,會出現錯誤

 1 def showtime(func):
 2     def inner(uid):
 3         import time
 4         print(time.localtime())
 5         res = func(uid)
 6         print(time.localtime())
 7         return res
 8     return inner
 9 
10 
11 @app.route('/<regex("d+"):uid>/', endpoint="index")
12 @showtime
13 def index(uid):
14     return "Hello {}".format(uid)

為了保留被裝飾函數的元信息,必須使用

 1 from functools import wraps
 2 
 3 
 4 def showtime(func):
 5     @wraps(func)
 6     def inner(uid):
 7         import time
 8         print(time.localtime())
 9         res = func(uid)
10         print(time.localtime())
11         return res
12     return inner
13 
14 
15 @app.route('/<regex("d+"):uid>/', endpoint="index")
16 @showtime
17 def index(uid):
18     return "Hello {}".format(uid)

總結

以上是生活随笔為你收集整理的四、添加路由的两种方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。