四、添加路由的两种方式
在Flask中,添加路由有兩種方式:(一般情況下都是用第一種方式)
第一種:常見的裝飾器模式
@app.route("/")
def index():
return "Hello World"
通過這種方式,將rule與視圖函數(shù)對應起來
第二種:通過閱讀裝飾器模式添加路由的源碼發(fā)現(xiàn)
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與視圖函數(shù)的對應關系的,所以可以這樣添加,
def home():
return "Hello, home!"
app.add_url_rule("/home", endpoint=None, view_func=home)
endpoint:給rule起一個別名,相當于django path路由函數(shù)中的name。
如何使用通過別名(endpoint)找到rule呢?(如果不起別名,就默認為函數(shù)名)
@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!"
===================================================================================================================================
如何通過路由傳遞參數(shù)呢?<轉換器:參數(shù)名>
@app.route("/<int:uid>/", endpoint="index")
def index(uid):
return "Hello {}".format(uid)
常用的轉換器:int、float、path、uuid、string、any、default
不難發(fā)現(xiàn),沒有正則表達式的轉換器,那么我們可以自定義:
1 class RegexConverter(BaseConverter):
2 def __init__(self, map, regex):
3 super(RegexConverter, self).__init__(map)
4 # 為什么只用賦值regex就可以了呢?其他轉化器是在類屬性regex(正則表達式)的基礎上實現(xiàn)的
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 # 雖然我們已經(jīng)定制好了正則轉換器類,但是應用程序不知道,我們還要通知一下
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)
參數(shù)通過**values傳遞:url_for(endpoint="index", uuid=10)
===================================================================================================================================
app.route方法常見的參數(shù):
rule:URL規(guī)則
view_func:視圖函數(shù)的名稱
default:默認值,當URL中無參數(shù),函數(shù)需要參數(shù)時,使用default={'k':'v'}為函數(shù)提供參數(shù)
endpoint:名稱,用于反向生產(chǎn)URL,即:url_for('名稱')
strict_slashes=None:對URL最后的/符號是否嚴格要求
redirect_to=None:重定向到指定地址
subdomain=None:子域名訪問
==================================================================================================================================
路由重點:url、methods、endpoint、int轉換器、url_for
==================================================================================================================================
如何給視圖函數(shù)添加裝飾器?
裝飾器要放在app.route的下面(放在上面,只會執(zhí)行一次),并且必須要保留被裝飾函數(shù)的元信息,因為當我們使用一個裝飾器去裝飾多個函數(shù)時,不保留被裝飾函數(shù)的元信息,endpoint會默認為函數(shù)名,這樣就會都等于裝飾器函數(shù)內部被返回的函數(shù)名,導致endpoint重名,會出現(xiàn)錯誤
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)
為了保留被裝飾函數(shù)的元信息,必須使用
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)
總結
以上是生活随笔為你收集整理的四、添加路由的两种方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 中国抗日战争时期牺牲了多少爱国名将
- 下一篇: 免疫力低下的表现(一般免疫力低的人)