我们在

Sanic HTTP 响应

中已经学习了响应的流式传输。实际上,Sanic还支持请求的流式传输。

请求流

下面的例子,当请求结束,

await request.stream.read()

返回

None

。只有

post, put, patch

修饰器有流参数。

from sanic import Sanic

from sanic.views import CompositionView

from sanic.views import HTTPMethodView

from sanic.views import stream as stream_decorator

from sanic.blueprints import Blueprint

from sanic.response import stream, text

bp = Blueprint('blueprint_request_stream')

app = Sanic('request_stream')

class SimpleView(HTTPMethodView):

@stream_decorator

async def post(self, request):

result = ''

while True:

body = await request.stream.read()

if body is None:

break

result += body.decode('utf-8')

return text(result)

@app.post('/stream', stream=True)

async def handler(request):

async def streaming(response):

while True:

body = await request.stream.read()

if body is None:

break

body = body.decode('utf-8').replace('1', 'A')

await response.write(body)

return stream(streaming)

@bp.put('/bp_stream', stream=True)

async def bp_put_handler(request):

result = ''

while True:

body = await request.stream.read()

if body is None:

break

result += body.decode('utf-8').replace('1', 'A')

return text(result)

# You can also use `bp.add_route()` with stream argument

async def bp_post_handler(request):

result = ''

while True:

body = await request.stream.read()

if body is None:

break

result += body.decode('utf-8').replace('1', 'A')

return text(result)

bp.add_route(bp_post_handler, '/bp_stream', methods=['POST'], stream=True)

async def post_handler(request):

result = ''

while True:

body = await request.stream.read()

if body is None:

break

result += body.decode('utf-8')

return text(result)

app.blueprint(bp)

app.add_route(SimpleView.as_view(), '/method_view')

view = CompositionView()

view.add(['POST'], post_handler, stream=True)

app.add_route(view, '/composition_view')

if __name__ == '__main__':

app.run(host='127.0.0.1', port=8000)

响应流

Sanic 允许我们使用

stream

方法向客户端流式传输内容。该方法接受一个带有

StreamingHTTPResponse

对象参数用以写操作的协程回调函数。比如下面的例子:

from sanic import Sanic

from sanic.response import stream

app = Sanic(__name__)

@app.route("/")

async def test(request):

async def sample_streaming_fn(response):

await response.write('foo,')

await response.write('bar')

return stream(sample_streaming_fn, content_type='text/csv')

这在将源自外部服务(如数据库)的内容流式传输给客户端的情况下非常有用。例如,我们可以使用

asyncpg

提供的异步游标将数据库记录流式传输到客户端:

@app.route("/")

async def index(request):

async def stream_from_db(response):

conn = await asyncpg.connect(database='test')

async with conn.transaction():

async for record in conn.cursor('SELECT generate_series(0, 10)'):

await response.write(record[0])

return stream(stream_from_db)

python sanic_Python Web框架Sanic Streaming – 流式传输相关推荐

  1. python框架sanic_Python Web框架Sanic框架初识

    Sanic 既是一个Python web 服务器,又是一个web框架,它为速度而生.Sanic只支持Python 3.5及其以上版本,允许我们使用 async/await 语法来使我们的代码非阻塞且快 ...

  2. python 流式编程_使用Python在两台计算机之间流式传输实时视频

    Video Streaming Demonstration

  3. 一个包含30行代码的Python项目:如何在您最喜欢的Twitcher流式传输时设置SMS通知...

    Hi everyone :) Today I am beginning a new series of posts specifically aimed at Python beginners. Th ...

  4. python bottle web框架简介

    Bottle 是一个快速,简单,轻量级的 Python WSGI Web 框架.单一文件,只依赖 Python 标准库 .bottle很适合会一点python基础的人使用,因为这框架用起来很简单,只要 ...

  5. python搭建django框架,Python之Web框架Django项目搭建全过程

    Python之Web框架Django项目搭建全过程 IDE说明: Win7系统 Python:3.5 Django:1.10 Pymysql:0.7.10 Mysql:5.5 注:可通过pip fre ...

  6. 比我的脸还干的gan货——Python Flask Web 框架入门

    Flask是一个轻量级的基于Python的web框架. 本文适合有一定HTML.Python.网络基础的同学阅读. 1. 简介 这份文档中的代码使用 Python 3 运行. 是的,所以读者需要自己在 ...

  7. API接口开发其实特简单,Python Flask Web 框架教程来了

    大家好,日常工作中,无论你是数据工程师.数据挖掘工程师,甚至数据分析人员,都不可避免的与他人进行数据交互,API接口提供数据是最常见的形式. 今天我给大家分享 Python Flask Web 框架教 ...

  8. python的Web框架Django运行报错:Invalid HTTP_HOST header: 'xxx.xx.xxx.xxx:8000'. You may need to add 'xxx.xx'

    python的Web框架Django运行报错:Invalid HTTP_HOST header: 'xxx.xx.xxx.xxx:8000'. You may need to add 'xxx.xx' ...

  9. Spark Streaming示例–如何从Slack流式传输

    让我们在Scala中编写一个Spark Streaming示例,该示例从Slack流传输. 这篇文章将首先展示如何编写,配置和执行代码. 然后,将详细检查源代码. 如果您没有Slack团队,则可以免费 ...

  10. python写一个app接收摄像头传输的视频_使用Python的Flask框架实现视频的流媒体传输...

    Flask 是一个 Python 实现的 Web 开发微框架.这篇文章是一个讲述如何用它实现传送视频数据流的详细教程. 我敢肯定,现在你已经知道我在O'Reilly Media上发布了有关Flask的 ...

最新文章

  1. BGP local-preference MED属性实验
  2. cmd mysql_CMD命令操作MySql数据库的方法详解
  3. 算法学习:manacher
  4. linux 系统监控 php,Linux系统资源监控命令简介
  5. Oracle数据库查询优化
  6. 明白90/10的原理吗?
  7. 超越界限,定义未来-- HP刀片工作站WS460c Gen9无惧4K挑战
  8. 蓝桥杯 BASIC-10 基础练习 十进制转十六进制
  9. bandzip、winzip与7-zip
  10. 想成为一名数据科学家?你得先读读这篇文章
  11. 戴尔要求DEC雇员扔掉Mac
  12. Zookeeper的数据模型和节点类型
  13. bilibili 2021 技术对抗赛 算法与安全答题 答案
  14. web入门 命令执行 web53-web55
  15. h5 加载完成_从零到一:实现通用一镜到底 H5
  16. 十大科学谜题本世纪有望解开:时间是幻觉吗
  17. 一下子搞懂JDBC,看这篇就够了--以MySQL为例。
  18. 各版本Eclipse安装WindowBuilder
  19. zerotier使用教程_zerotier简明教程
  20. Java实现GitHub第三方登录详解

热门文章

  1. mapper扫描问题(Invalid bound statement (not found))
  2. z变换解差分方程例题_Z变换解差分方程的思考
  3. 【DM642】ICELL Interface—Cells as Algorithm Containers
  4. Three.js地球开发—1.经纬度转球面坐标
  5. 静态库调用其它静态库
  6. MAC 系统下怎么新建一个桌面
  7. iPhone XR/XS/XS Max 适配,最全iPhone尺寸
  8. Python排序算法(四)——插入排序
  9. [编辑本段]【通古斯大爆炸六大热门假说】
  10. 有一个做饭好吃的妈妈是一种什么体验?