python - 使用 django 进行 mp3 流传输的问题

标签 python django

我正在尝试弄清楚如何使用 django 流式传输 mp3 文件。我使用了 http://djangosnippets.org/snippets/365/ 中的一些代码帮助我解决这个问题。由于某种原因,下面的代码给我的文件大小比服务器上存储的实际文件小。下载窗口中显示的大小正确,但实际文件要小得多。我尝试使用下面的代码发送文本文件,它似乎工作得很好。我似乎无法弄清楚出了什么问题。

def play_song(request, id):
    song = Song.objects.get(pk=id)
    # song is an object which has a FileField name file
    filepath = os.path.join(MP3_STORAGE, song.file.name).replace('\\', '/')
    wrapper = FileWrapper(file(filepath))
    response = HttpResponse(wrapper, content_type='audio/mpeg')
    response['Content-Length'] = os.path.getsize(filepath.replace('/', '\\'))
    response['Content-Disposition'] = 'attachment; filename=%s' % song.file.name
    return response

最佳答案

你读过http://djangosnippets.org/snippets/365/上的评论了吗? ?尝试:

For people on Windows you'll need to specify "read binary" mode for anything other than a text file:

wrapper = FileWrapper(file(filename), "rb")

Got this working with a few tweaks:

wrapper = FileWrapper(open(filename, 'rb'))

关于python - 使用 django 进行 mp3 流传输的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9417911/

相关文章:

django - 使用 django manage.py runserver 开发时如何使用远程静态文件服务器

django -/在尝试写入只读数据库时出现OperationalError

python - python中 `itertools.combinations`的计算复杂度是多少?

python - Django - 从values()函数返回子级列表?

python - Pandas `read_json` 函数将字符串转换为 DateTime 对象,即使指定了 `convert_dates=False` attr

python - python中两个 "linked"列表的排列

python - 前后端分离时的Django CSRF

django - 为什么使用 Django 的 collectstatic 而不是直接从静态目录提供文件?

python - 我不知道通常使用python aiomysql。运行时间(当 aiomysql 不使用时)与 aiomysql 使用时的运行时间相同

python - Google 应用引擎后端