亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Sanic框架流式傳輸操作示例

 更新時間:2018年07月18日 09:27:58   作者:噴跑的豆子  
這篇文章主要介紹了Sanic框架流式傳輸操作,結(jié)合實例形式分析了Sanic通過流請求與響應(yīng)傳輸操作相關(guān)實現(xiàn)技巧與注意事項,需要的朋友可以參考下

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

簡介

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

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

請求流式傳輸

Sanic允許通過流獲取請求數(shù)據(jù),如下所示,當(dāng)請求結(jié)束時,request.stream.get()返回為None,只有post、putpatch 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 text
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
class 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 CompositionView
async 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)

更多關(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)文章

最新評論