Django 从 Popen 进程发送内容长度到 StreamingHttpResponse

Django send content-length to StreamingHttpResponse from a Popen process

我需要提供从大型 wav 文件实时创建的 ogg 文件。 我可以发送内容,但我不知道为什么要将数据的可变长度指示给 StreamingHttpResponse。

这是我的代码:

class OggAudioStreamer(object):

    def __init__(self, archivo):
        self.archivo = archivo

    def read(self, **kwargs):
        command = 'ffmpeg -i "{0}" -ac 1 -ar 22050 -acodec libvorbis -f ogg -'.format(self.archivo)
        args = split(command)
        response = Popen(args, stdout=PIPE, stderr=PIPE,
                         bufsize=8192, universal_newlines=False)
        response_iterator = iter(response.stdout.readline, b"")

        for resp in response_iterator:
            yield resp

def ogg_stream_response(request):
    data = OggAudioStreamer('SOME WAV FILE')
    stream = StreamingHttpResponse(data.read(), content_type='audio/ogg')
    return stream

如果我正确理解了你的问题,你需要在通过 StreamingHttpResponse 流式传输响应时发送 Content-Length header。如果是这种情况,那么这是不可能的,并且在 StreamingHttpResponse 文档中明确说明:

StreamingHttpResponse should only be used in situations where it is absolutely required that the whole content isn’t iterated before transferring the data to the client. Because the content can’t be accessed, many middlewares can’t function normally. For example the ETag and Content-Length headers can’t be generated for streaming responses.

在我看来,在请求处理期间对音频文件进行转码并不是一个好主意,因为您可以通过这种方式耗尽所有请求处理程序。相反,我会使用某种后台处理,例如 Celery.