标题在Pyramid中发送chunked二进制文件

Mar*_*oni 2 python streaming pyramid

我有这个名为dummy的视图,我想从我的服务器流式传输mp3,我想将它流式传输到<audio src="/stream">标签,以便客户端可以立即开始播放文件,而无需等待整个文件.

def dummy(request):
    headers = {
        'Content-Transfer-Encoding': 'binary',
        'Content-Type': 'audio/mpeg',
        'Transfer-Encoding': 'chunked',
        'Connection': 'keep-alive',
        'Cache-Control': 'no-cache'
    }
    with open('songer.mp3') as handle:
        while True:
            bytes = handle.read(CHUNK)
            if not bytes:
                break
            return Response(bytes, headers=headers)
Run Code Online (Sandbox Code Playgroud)

但是我ERR_INVALID_CHUNKED_ENCODING从chrome 那里得到了,我也不确定我返回响应的方式是否会起作用,因为它一旦返回就不会结束响应?

Ser*_*gey 5

你是对的,你不能从视图中返回多个响应...或者,实际上,通常从循环中的函数发出多个返回 - 第一个return语句将终止该函数.

看看Response.body_fileResponse.app_iter属性.

response.app_iter: 将生成响应内容的可迭代(例如列表或生成器).这也可以作为response.body(一个字符串),response.unicode_body(一个unicode对象,由response.charset通知)和response.body_file(一个类似文件的对象;写入它附加到app_iter)访问

body_file类似文件的对象,可用于写入正文.如果您传入了一个列表app_iter,该app_iter将被写入修改.

http://docs.pylonsproject.org/projects/pyramid/en/latest/api/response.html

如果你做的事情

request.response.body_file = open('songer.mp3')
# set any headers here
return response
Run Code Online (Sandbox Code Playgroud)

该文件将从磁盘读取并立即发送到客户端,而无需等待整个文件.我不确定这里是否需要分块传输编码.

WebOb文档有一个更复杂的文件服务应用程序示例,它可以有效地处理Range请求:http://docs.webob.org/en/latest/file-example.html