使用Sanic框架怎么实现一个流式传输操作

  介绍

本篇文章给大家分享的是有关使用Sanic框架怎么实现一个流式传输操作,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

<强>简介

Sanic是一个类似瓶的Python 3.5 + Web服务器,它的写入速度非常快。除了瓶之外,Sanic还支持异步请求处理程序。这意味着你可以使用Python 3.5中新的闪亮的异步/等待语法,使你的代码非阻塞和快速。

在前面一篇《Sanic框架饼干操作》中已经讲到,如何在Sanic中使用饼干,接下来将介绍一下Sanic的流的使用:

<强>请求流式传输

Sanic允许通过流获取请求数据,如下所示,当请求结束时,<代码> request.stream.get() 返回为<代码> ,只有<代码> ,<代码>把和<代码>补丁装饰> 得到sanic.response  import 流   @app.post (“/post_stream"流=True)   async  def  post_stream(请求):   async 才能;def 流媒体(反应):   ,,,while 正确的:   ,,,,,body =, await  request.stream.get ()   ,,,,,if  body  is 没有:   ,,,,,,,休息   ,,,,,body =, body.decode (“utf-8")   ,,,,,reponse.write(身体)   return 才能流(流)   @app.put (“/put_stream"流=True)   async  def  put_stream(请求):   async 才能;def 流媒体(反应):   ,,,while 正确的:   ,,,,,body =, await  request.stream.get ()   ,,,,,if  body  is 没有:   ,,,,,,,休息   ,,,,,body =, body.decode (“utf-8")   ,,,,,response.write (“utf-8")   return 才能流(流)

除了上述例子的方法之外,我们之前还讲过用<代码> add_route 方法动态添加路由:

得到sanic.response  import 文本   得到sanic.views  import  HTTPMethodView   得到sanic.views  import  stream  as  stream_decorator   class  StreamView (HTTPMethodView)   @stream_decorator才能   async 才能;def  post(自我,请求)   ,,,result =, & # 39; & # 39;   ,,,while 正确的:   ,,,,,body =, await  request.stream.get ()   ,,,,,if  body  is 没有:   ,,,,,,,休息   ,,,,,body =, body.decode (& # 39; utf - 8 # 39;)   ,,,,,result  +=,身体   ,,,return 文本(结果)   app.add_route (StreamView.as_view (),“/method_view")

值得注意的是,<代码> stream_decorator 装饰器中处理函数的函数名称,若为邮报》则为文章请求,若为把则为把请求。在之前讲述路由的文章《Sanic框架路由用法》中讲到一个<代码> CompositionView> CompositionView> 得到sanic.views  import  CompositionView   async  def  post_stream_view(请求):   时间=result 才能;& # 39;& # 39;   while 才能正确的:   ,,,body =, await  request.stream.get ()   ,,,if  body  is 没有:   ,,,,,休息   ,,,body =, body.decode (& # 39; utf - 8 # 39;)   ,,,result  +=,身体   return 才能;文本(结果)   时间=view  CompositionView ()   view.add([& # 39;文章# 39;],post_stream_view,流=True)   app.add_route(看来,“/post_stream_view")

<强>响应流式传输

Sanic允许你使用<代码> 流方法将内容传输到客户端,该方法接受一个通过<代码> StreamingHTTPResponse> 得到sanic.response  import 流   @app.route (“/post_stream_info",方法=[“POST"])   async  def  post_stream_info(请求):   async 才能;def 流媒体(反应):   ,,,response.write (“no")   ,,,response.write (“bug")   return 才能流(流)

以上就是使用Sanic框架怎么实现一个流式传输操作,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。

使用Sanic框架怎么实现一个流式传输操作