2

我想知道使用 Pyramid 从 GridFS 提供文件的最佳且可能最简单的方法是什么。我使用 nginx 作为代理服务器(用于 ssl)和女服务员作为我的应用程序服务器。

我需要能够提供的文件类型如下:mp3、pdf、jpg、png

这些文件应该可以通过以下 url "/files/{userid}/{filename}" 访问

现在文件由客户端的正确应用程序打开,因为我在我的代码中明确设置了内容类型,如下所示:

if filename[-3:] == "pdf":
    response = Response(content_type='application/pdf')

elif filename[-3:] in ["jpg", "png"]:
    response = Response(content_type='image/*')

elif filename[-3:] in ["mp3"]:
    response = Response(content_type='audio/mp3')

else:
    response = Response(content_type="application/*")

response.app_iter = file   #file is a GridFS file object
return response

唯一的问题是我无法正确播放 mp3。我使用audio.js来播放它们。它们打开并播放,但没有显示音轨长度,我无法找到它们。我知道它与“接受范围”属性有关,但我似乎无法正确设置它。它与nginx或服务员有关吗?或者我只是没有正确设置标题?

我想使用像这里return FileResponse(file)指定的那样简单的东西,但我的文件不是直接来自文件系统......有没有即插即用的方式来完成这项工作?

任何建议将不胜感激!

非常感谢您的帮助!

4

3 回答 3

1

我在这个博客上找到了解决方案。

这个想法是使用一个DataApppaste.fileapp. 所有详细信息都在帖子中,现在我的应用程序的行为就像我想要的一样!

于 2013-01-29T00:11:07.217 回答
1

我刚刚在 Pyramid 1.4、Python 3 中解决了没有粘贴依赖的问题。

似乎属性“conditional_response=True”和“content_length”很重要:

f = request.db.fs.files.find_one( { 'filename':filename, 'metadata.bucket': bucket } )

fs = gridfs.GridFS( request.db )

with fs.get( f.get( '_id') ) as gridout:
    response = Response(content_type=gridout.content_type,body_file=gridout,conditional_response=True)
    response.content_length = f.get('length')
    return response
于 2013-10-14T14:17:11.417 回答
0

另一种方式(在 Python 2.7 上使用 Pyramid 1.5.7):

fs = GridFS(request.db, 'MyFileCollection')
grid_out = fs.get(file_id)

response = request.response
response.app_iter = FileIter(grid_out)
response.content_disposition = 'attachment; filename="%s"' % grid_out.name

return response
于 2015-07-21T05:49:41.033 回答