Sanic框架路由用法實(shí)例分析
本文實(shí)例講述了Sanic框架路由用法。分享給大家供大家參考,具體如下:
前面一篇《Sanic框架安裝與簡(jiǎn)單入門》簡(jiǎn)單介紹了Sanic框架的安裝與基本用法,這里進(jìn)一步學(xué)習(xí)Sanic框架的路由。
簡(jiǎn)介
Sanic是一個(gè)類似Flask的Python 3.5+ Web服務(wù)器,它的寫入速度非??臁3薋lask之外,Sanic還支持異步請(qǐng)求處理程序。這意味著你可以使用Python 3.5中新的閃亮的異步/等待語(yǔ)法,使你的代碼非阻塞和快速。
前言:Sanic最低支持Python 3.5,如果需要學(xué)習(xí)Sanic,請(qǐng)先下載版本不低于3.5的Python包
路由
路由允許用戶為不同的URL端點(diǎn)指定不同的處理函數(shù),我們?nèi)〕錾弦黄?a target="_blank" href="http://www.dbjr.com.cn/article/143843.htm">Sanic框架安裝與簡(jiǎn)單入門》的路由為例:
from sanic.response import json
@app.route("/")
async def hello_sanic(request):
data = json({"code":0})
return data
當(dāng)我們?cè)跒g覽器輸入http://localhost:5000/時(shí),根據(jù)路由匹配到處理函數(shù)hello_sanic,最終返回JSON對(duì)象。Sanic處理函數(shù)必須使用語(yǔ)法async def來定義,因?yàn)樗鼈兪钱惒叫袛?shù)。
請(qǐng)求參數(shù)
Sanic處理函數(shù)帶有一個(gè)支持請(qǐng)求的參數(shù),即上面的request參數(shù)。如果需要制定一個(gè)參數(shù),我們可以使用尖角括號(hào)將其括起來,如下所示:
from sanic.response import json
@app.route("/hello/<name>")
async def hello(request,name):
return json({"name":name})
此時(shí)我們?cè)贋g覽器輸入:http://localhost:5000/hello/laowang時(shí),Sanic將會(huì)根據(jù)路由匹配處理函數(shù),從而返回?cái)?shù)據(jù)。此時(shí),我們需要對(duì)參數(shù)進(jìn)行指定類型,可以在路由中的參數(shù)后面加上:type,假設(shè)傳入一個(gè)age參數(shù),為int類型,路由可以這么寫:/hello/<age:int>。代碼如下:
from sanic.response import json
@app.route("/hello/<age:int>")
async def hello_age(request,age):
return json({"age":age})
此時(shí)就可以指定用戶傳入指定類型的參數(shù)了,如果類型不對(duì),將報(bào)404錯(cuò)誤。
請(qǐng)求類型
對(duì)于Sanic處理網(wǎng)絡(luò)請(qǐng)求,也舉了不少例子,可是這些都是GET請(qǐng)求,那我們?cè)撊绾味x一個(gè)POST請(qǐng)求呢?與Flask相同,@app.route支持一個(gè)可選參數(shù)methods,methods可傳入一個(gè)列表類型,如此,它將允許處理函數(shù)使用列表中的任何HTTP方法。
from sanic.response import json
@app.route("/post/json_data",methods=["POST"])
async def post_json(request):
"""
POST請(qǐng)求 json數(shù)據(jù)
"""
return json(request.json)
@app.route("/post/form_data",methods=["POST"])
async def post_form(request):
"""
POST請(qǐng)求 form表單數(shù)據(jù)
"""
return json(request.form)
@app.route("/get/data",methods=["GET"])
async def get_data(request):
"""
GET請(qǐng)求
"""
return json(request.args)
因?yàn)?span style="color: #0000ff">GET請(qǐng)求時(shí)默認(rèn)的,所以,如果需要定義一個(gè)GET請(qǐng)求,那么methods參數(shù)可以無(wú)需傳遞。@app.route還支持另一個(gè)可選參數(shù)host,這限制了一條到所提供的主機(jī)或主機(jī)的路由。
from sanic.response import text
@app.route("/hello/host",host="abc.com")
async def hello_host(request):
return text("hello host")
在瀏覽器中訪問此路由,如果主機(jī)頭不匹配abc.com,那么將會(huì)報(bào)404錯(cuò)誤。
路由的裝飾器寫法除了上面介紹的那種,還可以將其簡(jiǎn)寫,如下所示:
from sanic.response import json
@app.get("/short/get")
async def short_get(request):
return json(request.args)
@app.post("/short/post")
async def short_post(request):
return json(request.json)
add_route方法
通常我們指定一個(gè)路由,都是通過@app.route裝飾器,然而,這個(gè)裝飾器實(shí)際上只是這個(gè)add_route方法的一個(gè)包裝器,使用方法如下:
async def add_get_route(request):
"""
添加GET請(qǐng)求
"""
return json(request.args)
async def add_get_type_route(request,age):
"""
添加帶指定類型的參數(shù)的GET請(qǐng)求
"""
return json({"age":age})
async def add_post_route(request):
"""
添加POST請(qǐng)求
"""
return json(request.json)
app.add_route(add_get_route,"/add_get_route")
app.add_route(add_get_type_route,"/add_get_type_route/<age:int>")
app.add_route(add_post_route,"/add_post_route",methods=["POST"])
重定向
Sanic提供了一個(gè)url_for基于處理程序方法名稱生成URL的方法。如果你想要避免將URL路徑硬編碼到你的應(yīng)用程序當(dāng)中,這很有用。例如:
from sanic.response import text,redirect
@app.route("/url_info")
async def url_info(request):
url = app.url_for('post_handler',name="laozhang",arg_one="one",arg_two="two")
print(url)
return redirect(url)
@app.route("/post_handler/<name>")
async def post_handler(request,name):
print(request.args)
return text("name:{}".format(name))
url_for使用注意:第一個(gè)參數(shù)為重定向URL的路由名稱(默認(rèn)為函數(shù)名稱),并非URL名稱。另外我們可以將一些請(qǐng)求參數(shù)指派到url_for方法中,上面例子重定向后的url將會(huì)是:
/post_handler/laozhang?arg_one=one&arg_two=two
也可以傳遞多值參數(shù):
app.url_for("post_handler",favorite=["football","bastketball"])
# /post_handler?favorite=football&favorite=bastketball
唯一URL
在Flask中,我們頂一個(gè)一個(gè)URL為/get,此時(shí)我們?cè)L問/get將可以訪問成功,如果輸入/get/將會(huì)返回404錯(cuò)誤,這就是唯一URL。在Sanic中同樣擁有此功能,我們可以通過配置strict_slashes參數(shù)來實(shí)現(xiàn):
from sanic.response import text
@app.route("/get",strict_slashes=True)
async def get(request):
return text("it is ok!")
注意:strict_slashes默認(rèn)值為None,如果不設(shè)置的話,訪問/get或/get/都將可以訪問成功,那么這就不是唯一URL了。在上面的例子中,我們將此值設(shè)置為True,此時(shí)我們輸入/get/,將會(huì)返回一個(gè)404錯(cuò)誤,這樣就完成了一個(gè)唯一URL的實(shí)現(xiàn)。
如果我們需要將所有的URL都設(shè)置成為唯一URL,我們可以這樣:
from sanic import Sanic
from sanic.response import text
app = Sanic(strict_slashes=True)
@app.route("/hello")
async def hello(request):
return text("it is ok!")
@app.route("/world")
async def world(request):
return text("it is ok!")
/hello和world都變成了唯一URL。
如果我們只需要部分URL設(shè)置成唯一URL,我們可以在@app.route裝飾器中傳入strict_slashes,并設(shè)置為Flase,那么此URL將不是唯一URL。或者我們也可以定義一個(gè)藍(lán)圖,如下:
from sanic import Blueprint
ss_bp = Blueprint("aaa",strict_slashes=False)
@ss_bp.route("/world")
async def world(request):
return text("it is ok!")
app.blueprint(ss_bp)
即使你在app中傳遞了參數(shù)strict_slashes=True,那么也沒有用,所有通過此藍(lán)圖定義的URL都將不是唯一URL。
自定義路由名稱
通常一個(gè)路由的名稱為程序處理方法名稱,即函數(shù).__name__生成的,用于可以傳遞一個(gè)name參數(shù)到裝飾器中來修改它的名稱,如下:
from sanic.response import text
@app.route("/get",name="get_info")
async def get(request):
return text("it is ok!")
此時(shí)url_for中傳遞的將不是函數(shù)名稱,而是name的值:
print(app.url_for("get_info")) # /get
同樣,也適用于藍(lán)圖:
from sanic import Blueprint
ss_bp = Blueprint("test_bp")
@ss_bp.route("/get",name="get_info")
async def get(request):
return text("it is ok!")
app.blueprint(ss_bp)
print(app.url_for("test_bp.get_info"))
靜態(tài)文件的URL
我們需要構(gòu)建一個(gè)特定的URL來訪問我們需要的HTML,此時(shí)我們可以這樣:
from sanic import Sanic,Blueprint
app = Sanic()
app.static("/home","./static/home.html")
此時(shí)我們?cè)谠L問/home就可以鏈接到我們指定的HTML中了,此方法同樣適用于藍(lán)圖。
CompositionView
除了上面那幾種定義路由的方法之外,Sanic還提供了CompositionView來動(dòng)態(tài)添加路由:
from sanic.views import CompositionView
from sanic.response import text
async def post_handler(request):
print(request.json)
return text('it is ok!')
view = CompositionView()
view.add(["POST"],post_handler)
app.add_route(view,"/post_info")
如此,就構(gòu)造了一個(gè)POST請(qǐng)求的接口
處理器裝飾器
由于Sanic處理程序是簡(jiǎn)單的Python函數(shù),因此可以用與Flask類似的修飾符應(yīng)用于它們。一個(gè)典型的用例就是當(dāng)一些代碼想要在處理程序的代碼執(zhí)行之前執(zhí)行:
from sanic.response import text
def is_authorized():
return True
def authorized(func):
async def wrapper(request,*args,**kwargs):
is_auth = is_authorized()
if is_auth:
response = await func(request,*args,**kwargs)
return response
else:
return text("it is not authorized")
return wrapper
@app.route("/get_user_info")
@authorized
async def get_user_info(request):
return text("get_user_info")
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python入門與進(jìn)階經(jīng)典教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python文件與目錄操作技巧匯總》
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python中SyntaxError: invalid syntax報(bào)錯(cuò)解決
在編寫Python代碼時(shí),常見的SyntaxError錯(cuò)誤通常由括號(hào)不匹配、關(guān)鍵字拼寫錯(cuò)誤或不正確的縮進(jìn)引起,本文詳細(xì)介紹了錯(cuò)誤原因及多種解決方案,包括檢查括號(hào)、關(guān)鍵字,以及使用IDE的語(yǔ)法檢查功能等,感興趣的可以了解一下2024-09-09
Win10下配置tensorflow-gpu的詳細(xì)教程(無(wú)VS2015/2017)
這篇文章主要介紹了Win10下配置tensorflow-gpu(無(wú)VS2015/2017),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
Pytorch?和?Tensorflow?v1?兼容的環(huán)境搭建方法
這篇文章主要介紹了搭建Pytorch?和?Tensorflow?v1?兼容的環(huán)境,本文是小編經(jīng)過多次實(shí)踐得到的環(huán)境配置教程,給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-11-11
Django項(xiàng)目在pycharm新建的步驟方法
在本篇文章里小編給大家整理的是一篇關(guān)于Django項(xiàng)目在pycharm新建的步驟方法,有興趣的朋友們可以學(xué)習(xí)參考下。2021-03-03

