django对静态文件进行身份验证
我有一组静态文件(通过应用程序上传),例如图像、视频等,需要提供给经过身份验证的用户(即他们的 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
I have a set of static files (that get uploaded through the application) like images, video, etc. that need to be served to authenticated users (i.e. their cookie is registered as authenticated in the session).
These files are separate and in no way related to other media static files like css, javaacript, etc.
Given that my static files that need to be authenticated will be fairly large, I was wondering what would be the most efficient way of serving them (btw, i'm using wsgi).
Currently I have this:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我目前正在使用与您上面使用的类似的功能。
我在想一旦性能/效率成为问题,我会使用 Apache mod-auth-external 对给定文件进行自定义授权。
请注意,我提供这个答案不是基于我的经验,而是基于我自己的研究。
I'm currently using a function similar to what you use above.
I was thinking once performance/efficiency became an issue, I would use Apache mod-auth-external to do my custom authorization for a given file.
Please note, I offer this answer not based on my experience, but where my own research led me.