flask原始碼之路由系統本質 二

2021-08-27 11:23:01 字數 1554 閱讀 3743

flask的路由比較特殊,是基於裝飾器來實現的,但是究其本質還是通過乙個方法來實現的,什麼方法呢,請看下面

我們先寫個簡單列子:

from flask import flask

'''2.@decorator

'''def

hello_world

():return

'hello world!'

if __name__ == '__main__':

第一步先執行route()函式,我們點開route()看裡面原始碼有這樣一段:

def

route

(self, rule, **options):

#rule = /

#options =

defdecorator

(f):

endpoint = options.pop('endpoint', none)

self.add_url_rule(rule, endpoint, f, **options)

return f

return decorator

從上面可以看出,route你們就是這樣乙個,第一步其實就是將一些引數放到了作用域裡面相當於是乙個閉包,閉包給誰用,其實就是給以後誰執行這個函式就給誰用

第二步就是相當於執行了@decorator,就會立即執行裡面的decorator()函式,引數就是hello_world函式,看裡面的本質其實就是add_url_rule()這個方法,這個裡面包含了url,endpoint,以及函式。

所以新增路由對映的本質其實就是執行add_url_rule()方法

所以:

def

login

():return

'登入'

這樣寫也是能用的。

這兒還得注意下裡面的endpoint,如果endpoint沒傳值,是空的的話會怎麼樣,我們點開add_url_rule看裡面有一段這樣的原始碼:

if endpoint is

none:

endpoint = _endpoint_from_view_func(view_func)

view_func是函式,那這返回的是什麼呢,我們再找,點開_endpoint_from_view_func,看原始碼:

def

_endpoint_from_view_func

(view_func):

"""internal helper that returns the default endpoint for a given

function. this always is the function name.

"""assert view_func is

notnone, 'expected view func if endpoint ' \

'is not provided.'

return view_func.__name__

其實返回的就是函式名。所以我們如果endpoint不寫的話,預設是函式名。

Flask 之路由系統

flask中的路由系統其實我們並不陌生了,從一開始到現在都一直在應用 為什麼要這麼用?其中的工作原理我們知道多少?methods 當前 url 位址,允許訪問的請求方式 info methods get post defstudent info stu id int request.args id ...

Flask入門之 路由

測試flask的路由,新增路由的方式有兩種 1 方法前面加 測試了這個方法 瀏覽器中的位址為 或者 hello 才正常 hello 報錯還沒查到原因,查到以後再更新 測試 如下 from flask import flask 路由固定 def hello world return hello wor...

Flask 路由系統

反向生成url def index print index print url for n1 return index 動態路由 def index nid print url for index nid 777 print url for index nid nid 根據輸入的nid,反向生成ur...