我需要根据特定的逻辑返回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)
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)
| 归档时间: |
|
| 查看次数: |
18736 次 |
| 最近记录: |