访问用户上传视频的临时存储问题
我正在尝试通过一个 HTML 输入框上传用户的视频到 YouTube,使用的是一个叫做 youtube-upload 的 Python 模块。当我提交表单时,处理方式如下:
if request.method == 'POST':
video = request.FILES['file']
v=str(video)
command = 'youtube-upload --email=email@gmail.com --password=password --title=title --description=description --category=Sports ' + v
r = subprocess.Popen(command, stdout=subprocess.PIPE)
v = r.stdout.read()
所以我猜问题可能是我需要提供一个更完整的视频路径。如果真是这样的话,怎样才能找到临时内存中视频的路径呢?
这个命令的一般格式是:
youtube-upload --email=email --password=password --title=title --description=description --category=category video.avi
另外,我还查看了 YouTube 的 API,特别是在 这里,但如果有人能提供一个更详细的解释,教我如何用 Python 和这个 API 来做,那就太好了。不幸的是,网站上的指南只关注 XML 部分。
根据 sacabuche 的评论,我现在的想法大致是:
def upload_video(request):
if request.method == 'POST':
video = request.FILE['file']
v = video.temporary_file_path
command = 'youtube-upload --email=email@gmail.com --password=password --title=title --description=description --category=Sports ' + v
r=subprocess.Popen(command, stdout=subprocess.PIPE)
vid = r.stdout.read()
else:
form = VideoForm()
request.upload_handlers.pop(0)
return render_to_response('create_check.html', RequestContext(request, locals() ) )
但是 v=video.temporary_file_path
报错了,提示 'InMemoryUploadedFile' object has no attribute 'temporary_file_path'
。所以视频仍然在临时内存中,我不知道 temporary_file_path
应该在哪个对象上调用,或者我该如何获取这个对象。
1 个回答
其实,Django会把文件保存在内存里,但大文件会保存在一个特定的路径下。
“大文件”的大小可以在设置中通过 FILE_UPLOAD_MAX_MEMORY_SIZE
来定义。
而默认的 FILE_UPLOAD_HANDLERS
是:
("django.core.files.uploadhandler.MemoryFileUploadHandler",
"django.core.files.uploadhandler.TemporaryFileUploadHandler",)
这给我们提供了两种选择:
1. 移除内存处理器
如果你移除 ..MemoryFileUploadHandler
,那么所有的文件都会保存在一个临时文件里,这样就不太方便了。
2. 动态修改处理器
#views.py
def video_upload(request):
# this removes the first handler (MemoryFile....)
request.upload_handlers.pop(0)
return _video_upload(request)
def _video_upload(request):
....
要获取文件的路径,你只需要使用 video.temporary_file_path
。