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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Flask的endpoint的理解

發布時間:2024/1/1 编程问答 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Flask的endpoint的理解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在flask框架中,我們經常會遇到endpoint這個東西,最開始也沒法理解這個到底是做什么的。最近正好在研究Flask的源碼,也就順帶了解了一下這個endpoint

1、Flask路由是怎么工作

整個flask框架(及以Werkzeug類庫為基礎構建的應用)的程序理念是把URL地址映射到你想要運行的業務邏輯上(最典型的就是視圖函數),例如:

from flask import Flask app = Flask(__name__)@app.route("/index/") def index1():return '{"key1":1,"key2":2}'

注意,add_url_rule函數實現了同樣的目的,只不過沒有使用裝飾器,因此,下面的程序是等價的:

def index3():return '{"key1":1,"key2":2}' app.add_url_rule("/index/",view_func=index3)

2、add_url_rule的介紹

這個add_url_rule函數在文檔中是這樣解釋的:

def add_url_rule(self,rule: str,endpoint: t.Optional[str] = None,view_func: t.Optional[t.Callable] = None,provide_automatic_options: t.Optional[bool] = None,**options: t.Any,)

add_url_rule有如下參數:

rule?– the URL rule as string
endpoint?– the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint
view_func?– the function to call when serving a request to the provided endpoint
options?– the options to be forwarded to the underlying 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.

拋開options這個參數不談,我們看看前三個參數。
rule:這個參數很簡單,就是匹配的路由地址
view_func:這個參數就是我們寫的視圖函數
endpoint:這個參數就是我今天重點要講的,endpoint

很多人認為:假設用戶訪問http://www.example.com/user/eric,flask會找到該函數,并傳遞name='eric',執行這個函數并返回值。
但是實際中,Flask真的是直接根據路由查詢視圖函數么?

在Flask的內部,每個核心對象都會維護二張表

url_map: 維護的是url和endpoint的映射關系

view_functions: 維護的是endpoint和function的映射關系

?所以我們可以看出:這個url_map存儲的是url與endpoint的映射!
回到flask接受用戶請求地址并查詢函數的問題。實際上,當請求傳來一個url的時候,會先通過rule找到endpoint(url_map),然后再根據endpoint再找到對應的view_func(view_functions)。通常,endpoint的名字都和視圖函數名一樣。
這時候,這個endpoint也就好理解了:

實際上這個endpoint就是一個Identifier,每個視圖函數都有一個endpoint, 當有請求來到的時候,用它來知道到底使用哪一個視圖函數

在實際應用中,當我們需要二條路由路徑顯示同一個頁面的時候,就可以在定義的方法的下面同時使用二個add_url_rule方法,路由地址分別寫為" / " 和"? /home ",endpoint分別顯示" index "與" index2 ",最后的view_func同時寫成一樣的index2就行了,最后二條路地址就可以顯示同一個頁面,

def index2():return "hello world" app.add_url_rule("/",endpoint="index",view_func=index2) app.add_url_rule("/home",endpoint="index2",view_func=index2)

這是在根目錄下顯示的效果:

?這是在/home目錄下顯示的效果:

?

?

endpoint 沒有明顯的定義的話,就會使用函數名字作為endpoint
endpoint在view_functions表需要全局唯一
endpoint函數名可以重復

總結

以上是生活随笔為你收集整理的Flask的endpoint的理解的全部內容,希望文章能夠幫你解決所遇到的問題。

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