如何返回通过django中的视图的静态文件?

Ste*_*ini 19 django

我需要根据特定的逻辑返回css文件和js文件.显然,静态服务并不能满足我的需求.我有一个视图,其render方法使用逻辑来查找正确的文件,但我必须返回它.从技术上讲,我可以只读取文件并将其填充到具有适当mime类型的HttpResponse对象中,但我想知道是否有更好的策略.(比如php中的fpassthru())

Uku*_*kit 22

这是我用过的:

test_file = open('/home/poop/serve/test.pdf', 'rb')
response = HttpResponse(content=test_file)
response['Content-Type'] = 'application/pdf'
response['Content-Disposition'] = 'attachment; filename="%s.pdf"' \
                                  % 'whatever'
return response
Run Code Online (Sandbox Code Playgroud)

  • 在我看来,这会导致整个文件被加载到内存中.不是吗? (2认同)

Ger*_*alt 10

你在用什么网络服务器软件?

至少对于Apache和NginX,有一个模块允许您使用X-SendFileHTTP标头.NginX网站称Lighty也可以做到这一点.

在你的包装器视图中:

...

abspath = '/most_secret_directory_on_the_whole_filesystem/protected_filename.css'

response = HttpResponse()
response['X-Sendfile'] = abspath

response['Content-Type'] = 'mimetype/submimetype'
# or let your webserver auto-inject such a header field
# after auto-recognition of mimetype based on filename extension

response['Content-Length'] = <filesize>
# can probably be left out if you don't want to hassle with getting it off disk.
# oh, and:
# if the file is stored via a models.FileField, you just need myfilefield.size

response['Content-Disposition'] = 'attachment; filename=%s.css' \
    % 'whatever_public_filename_you_need_it_to_be'

return response
Run Code Online (Sandbox Code Playgroud)

然后你可以通过连接视图http://mysite.com/url_path/to/serve_hidden_css_file/.

您可以随时使用它来处理请求的文件,这些文件不应该被用户直接访问,例如限制谁可以访问它,或者计算对stats的请求等等.

对于Apache:http://tn123.ath.cx/mod_xsendfile/
对于NginX:http://wiki.nginx.org/NginxXSendfile


小智 5

为什么不在视图中使用Django静态文件

from django.contrib.staticfiles.views import serve

...
def view_function(request):
   return serve(request, 'absolute_path_to_file_name')
Run Code Online (Sandbox Code Playgroud)

  • [docs](https://docs.djangoproject.com/en/1.4/ref/contrib/staticfiles/#other-helpers)说:"警告.这个视图只有在DEBUG为True时才有效.这是因为这个视图是效率极低,可能不安全.这只是用于本地开发,绝不能用于生产." (9认同)

Lak*_*sad -2

使用 django 来提供静态内容应该是一种浪费(更不用说,速度慢了几个数量级)。

我宁愿将视图转换为上下文处理器,并使用模板中的变量来查找要包含的块。