在django发送视频作为响应 [英] Sending video as response in django

查看:147
本文介绍了在django发送视频作为响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在django中发送视频mp4文件作为响应?我不想嵌入html的视频或对象标签,但是想发送mp4本身。任何人都可以帮忙解决这个问题?

How to send a video mp4 file as a response in django? I don't want to embed in a video or object tags of html, but want to send the mp4 itself. Can anyone please help with this issue?

推荐答案

一般来说,你不想这样做最好将重定向到非Django服务器到提供静态文件,例如 django.shortcuts.redirect - 它会更快,记忆效率更高,更安全。但是当然有时候不方便。这应该可以工作:

Generally you don't want to do this; it's better to redirect to a non-Django server to serve static files, with e.g. django.shortcuts.redirect -- it'll be faster, more memory-efficient, and probably more secure. But of course sometimes that's not convenient. This should work:

from wsgiref.util import FileWrapper

file = FileWrapper(open('path/to/video.mp4', 'rb'))
response = HttpResponse(file, content_type='video/mp4')
response['Content-Disposition'] = 'attachment; filename=my_video.mp4'
return response

FileWrapper docs )被使用,以便太多的数据不会立即发送,因为Python文件对象一次迭代一行,并且 \\\
字符在mp4中可能不是特别常见的。 (发送太多意味着网络服务器无法发送文件,因为它是从硬盘驱动器读取的,而是必须等待长的笨拙间隔的增量。)

The FileWrapper (docs) is used so that too much data isn't sent at once, since Python file objects iterate a line at a time, and \n characters presumably aren't especially common in mp4s. (Sending too much means that the webserver can't send the file as it's read off the hard drive but instead has to wait for long awkwardly-spaced increments.)

注意虽然我在文档中没有看到这一点,但文件完成后会关闭

Note that although I don't see this noted in the documentation anywhere, the file does get closed when it's done with.

这篇关于在django发送视频作为响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆