我有一组静态文件(通过应用程序上传),如图像、视频等,需要提供给经过身份验证的用户(即他们的 cookie 在会话中注册为经过身份验证)。
这些文件是独立的,与 css、javaacript 等其他媒体静态文件没有任何关系。
鉴于我需要进行身份验证的静态文件将相当大,我想知道为它们提供服务的最有效方式是什么(顺便说一句,我正在使用 wsgi)。
目前我有这个:
def return_large_file(request, p_filename):
"""
Send a file through Django without loading the whole file into
memory at once. The FileWrapper will turn the file object into an
iterator for chunks of 8KB.
"""
if not os.path.exists(p_filename):
raise Exception('File %s does not exist!')
try:
_content_type = mimetypes.guess_type(p_filename)
except:
_content_type = 'application/octet-stream'
wrapper = FileWrapper(file(p_filename))
response = HttpResponse(wrapper, content_type=_content_type)
response['Content-Length'] = os.path.getsize(p_filename)
return response