Sanic框架請求與響應(yīng)實例分析
本文實例講述了Sanic框架請求與響應(yīng)。分享給大家供大家參考,具體如下:
前面介紹了Sanic框架的路由,這里接著介紹Sanic框架的請求與響應(yīng)。
簡介
Sanic是一個類似Flask的Python 3.5+ Web服務(wù)器,它的寫入速度非??臁3薋lask之外,Sanic還支持異步請求處理程序。這意味著你可以使用Python 3.5中新的閃亮的異步/等待語法,使你的代碼非阻塞和快速。
前言:Sanic最低支持Python 3.5,如果需要學(xué)習(xí)Sanic,請先下載版本不低于3.5的Python包
請求數(shù)據(jù)
當(dāng)一個端點收到一個HTTP請求時,路由功能被傳遞到一個request對象。以下變量可以作為request對象的屬性訪問:
- json:JSON數(shù)據(jù)
@app.route("/post_data",methods=["POST"]) async def post_data(request): # 將打印傳遞過來的JSON數(shù)據(jù) print(request.json) return text("it is ok!")
- args:查詢字符串變量。查詢字符串是類似于URL的部分
?name=laozhang&age=20
。如果URL被解析,那么args字典將如下所示:{"name":["laozhang"],"age":[20]}
- raw_args:在許多情況下,我們需要獲取壓縮程度低的字典中的url參數(shù)。對于之前的
URL?name=laozhang&age=20
,raw_args
字典將如下所示:{"name":"laozhang","age":20}
- file:文件對象字典,具有名稱,正文和類型的文件列表
@app.route("/post_file_data",methods=["POST"]) async def post_file_data(request): info = request.files.get("file") print(info.name) print(info.type) print(info.body) return text("it is ok!")
- form:表單數(shù)據(jù),form字典將如下所示:
{"name":["laozhang"]}
@app.route("/post_form_data",methods=["POST"]) async def post_form_data(request): name = request.form.get("name") return text("it is ok!")
- body:原始數(shù)據(jù)。無論內(nèi)容類型如何,該屬性都允許檢索請求的原始數(shù)據(jù)。
byte
類型 - headers:獲取請求表頭的不區(qū)分大小寫的字典。
dict
類型 - ip:IP地址,
str
類型 - port:端口,
str
類型 - socket:請求者的IP地址和端口,(IP地址,端口)。
tuple
類型 - app:對處理請求的Sanic應(yīng)用程序?qū)ο蟮囊谩?/li>
@appr.route("/get_app_info") async def get_app_info(request): print(request.app.config) return text("it is ok!")
- url:請求的完整URL,如:http://localhost:5000/get_app_info
- scheme:獲取與請求關(guān)聯(lián)的URL方案:
http
或https
- host:獲取與請求關(guān)聯(lián)的主機
- path:獲取請求的路徑,如:
/get_app_info
- query_string:獲取查詢的字符串,如:
name=zhangsan
或者為一個空白字符串 - uri_template:獲取匹配路由處理程序的模板,如:
/get/<id>
- token:授權(quán)標(biāo)頭的值
get與getlist
當(dāng)我們訪問一個GET請求,并傳入相關(guān)參數(shù)時,如下的請求:
@app.route("/get_info") async def get_info(request): print(request.args.get("name")) print(request.args.getlist("name") return text("it is ok!")
當(dāng)我們傳入一個name
為laozhang
時,在上面有提到,args字典將會是{"name":["laozhang"]
,所以,訪問上面的路由,將會打印如下結(jié)果:
laozhang
["laozhang"]
響應(yīng)
使用sanic.response
模塊中的函數(shù)來創(chuàng)建響應(yīng)
純文本:
from sanic.response import text @app.route("/text") async def get_text(request): return text("it is text response!")
HTML:
from sanic.response import html @app.route("/html") async def get_html(request): return html("<p>it is html!</p>")
JSON:
from sanic.response import json @app.route("/json") async def get_json(request): return json({"name":"laozhang"})
FILE:
from sanic.response import file @app.route("/file") async def get_file(request): return await file("/xx/aa/abc.png")
切記,不能少了await
關(guān)鍵字
STREAM:
from sanic.response import stream @app.route("/stream") async def get_stream(request): async def stream_fn(response): response.write("abc") response.write("def") return stream(stream_fn,content_type="text/plain")
文件流:針對大文件,上面文件與流的組合
from sanic.response import file_stream @app.route("/file_stream") async def get_file_stream(request): return await file_stream("/xx/aa/abc.png")
切記,不能少了await
關(guān)鍵字
重定向:
from sanic.response import redirect @app.route("/redirect") async def get_redirect(request): return redirect("/json")
RAW:未編碼的body響應(yīng)
from sanic.response import raw @app.route("/raw") async def get_raw(request): return raw(b"it is raw data")
訪問此接口后,將會立即下載一個名為raw
的文件,里面包含內(nèi)容it is raw data
修改請求頭和狀態(tài)值:如果需要修改請求頭和狀態(tài)值,請將headers
和status
參數(shù)傳遞給上面這些函數(shù),下面以json
為例
from sanic.response import json @app.route("/json") async def get_json(request): return json({"name":"老張"},headers={"age":18},status=403)
訪問此接口后,會發(fā)現(xiàn)原來本應(yīng)是200的狀態(tài)值變成了403,而且請求頭信息中增加了{"age":18}
更多關(guān)于Python相關(guān)內(nèi)容可查看本站專題:《Python入門與進(jìn)階經(jīng)典教程》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設(shè)計有所幫助。
相關(guān)文章
Python RuntimeWarning:invalid value encounter
這篇文章主要介紹了Python RuntimeWarning:invalid value encountered in double_scalars處理,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06Python+Selenium使用Page Object實現(xiàn)頁面自動化測試
這篇文章主要介紹了Python+Selenium使用Page Object實現(xiàn)頁面自動化測試,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07使用Python、TensorFlow和Keras來進(jìn)行垃圾分類的操作方法
這篇文章主要介紹了如何使用Python、TensorFlow和Keras來進(jìn)行垃圾分類,這個模型在測試集上可以達(dá)到約80%的準(zhǔn)確率,可以作為一個基礎(chǔ)模型進(jìn)行后續(xù)的優(yōu)化,需要的朋友可以參考下2023-05-05python將logging模塊封裝成單獨模塊并實現(xiàn)動態(tài)切換Level方式
這篇文章主要介紹了python將logging模塊封裝成單獨模塊并實現(xiàn)動態(tài)切換Level方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05理解Python數(shù)據(jù)離散化手寫if-elif語句與pandas中cut()方法實現(xiàn)
這篇文章主要介紹了通過手寫if-elif語句與pandas中cut()方法實現(xiàn)示例理解Python數(shù)據(jù)離散化詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05