国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Sanic框架流式傳輸操作示例

2020-02-15 22:26:57
字體:
供稿:網(wǎng)友

本文實例講述了Sanic框架流式傳輸操作。分享給大家供大家參考,具體如下:

簡介

Sanic是一個類似Flask的Python 3.5+ Web服務(wù)器,它的寫入速度非常快。除了Flask之外,Sanic還支持異步請求處理程序。這意味著你可以使用Python 3.5中新的閃亮的異步/等待語法,使你的代碼非阻塞和快速。

在前面一篇《Sanic框架Cookies操作》中已經(jīng)講到,如何在Sanic中使用Cookie,接下來將介紹一下Sanic的流的使用:

請求流式傳輸

Sanic允許通過流獲取請求數(shù)據(jù),如下所示,當請求結(jié)束時,request.stream.get()返回為None,只有postputpatch decorator擁有流參數(shù):

from sanic.response import stream@app.post("/post_stream",stream=True)async def post_stream(request):  async def streaming(response):    while True:      body = await request.stream.get()      if body is None:        break      body = body.decode("utf-8")      reponse.write(body)  return stream(streaming)@app.put("/put_stream",stream=True)async def put_stream(request):  async def streaming(response):    while True:      body = await request.stream.get()      if body is None:        break      body = body.decode("utf-8")      response.write("utf-8")  return stream(streaming)

除了上述例子的方法之外,我們之前還講過用add_route方法動態(tài)添加路由:

from sanic.response import textfrom sanic.views import HTTPMethodViewfrom sanic.views import stream as stream_decoratorclass StreamView(HTTPMethodView)  @stream_decorator  async def post(self,request)    result = ''    while True:      body = await request.stream.get()      if body is None:        break      body = body.decode('utf-8')      result += body    return text(result)app.add_route(StreamView.as_view(),"/method_view")

值得注意的是,stream_decorator裝飾器中處理函數(shù)的函數(shù)名稱,若為post則為post請求,若為put則為put請求。在之前講述路由的文章《Sanic框架路由用法》中講到一個CompositionView類來自定義一個路由,CompositionView在流式請求中同樣適用:

from sanic.views import CompositionViewasync def post_stream_view(request):  result = ''  while True:    body = await request.stream.get()    if body is None:      break    body = body.decode('utf-8')    result += body  return text(result)view = CompositionView()view.add(['POST'],post_stream_view,stream=True)app.add_route(view,"/post_stream_view")

響應(yīng)流式傳輸

Sanic允許你使用stream方法將內(nèi)容傳輸?shù)娇蛻舳耍摲椒ń邮芤粋€通過StreamingHTTPResponse傳入的對象的協(xié)程回調(diào),舉個栗子:

from sanic.response import stream@app.route("/post_stream_info",methods=["POST"])async def post_stream_info(request):  async def streaming(response):    response.write("no")    response.write("bug")  return stream(streaming)            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 齐齐哈尔市| 尼勒克县| 米林县| 通海县| 永和县| 牟定县| 韶山市| 新巴尔虎右旗| 桂阳县| 吴旗县| 敖汉旗| 桦南县| 新余市| 新野县| 永新县| 宜城市| 阳东县| 四子王旗| 东港市| 华池县| 渭源县| 新巴尔虎右旗| 荣成市| 洞头县| 富源县| 阿克苏市| 上虞市| 彰武县| 长武县| 滦平县| 宁夏| 青河县| 贵定县| 久治县| 札达县| 鹤岗市| 略阳县| 临夏市| 天水市| 托克逊县| 高台县|