本篇文章給大家分享的是有關使用Sanic框架怎么實現一個流式傳輸操作,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
簡介
Sanic是一個類似Flask的Python 3.5+ Web服務器,它的寫入速度非???。除了Flask之外,Sanic還支持異步請求處理程序。這意味著你可以使用Python 3.5中新的閃亮的異步/等待語法,使你的代碼非阻塞和快速。
在前面一篇《Sanic框架Cookies操作》中已經講到,如何在Sanic中使用Cookie,接下來將介紹一下Sanic的流的使用:
請求流式傳輸
Sanic允許通過流獲取請求數據,如下所示,當請求結束時,request.stream.get()返回為None,只有post、put和patch decorator擁有流參數:
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方法動態添加路由:
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裝飾器中處理函數的函數名稱,若為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")響應流式傳輸
Sanic允許你使用stream方法將內容傳輸到客戶端,該方法接受一個通過StreamingHTTPResponse傳入的對象的協程回調,舉個栗子:
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)以上就是使用Sanic框架怎么實現一個流式傳輸操作,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。