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