如何通过django中的视图返回静态文件? [英] How to return static files passing through a view in django?

查看:391
本文介绍了如何通过django中的视图返回静态文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要根据具体的逻辑返回css文件和js文件。显然,静态服务不能执行我所需要的。我有一个视图,其渲染方法使用逻辑来找到正确的文件,但是我必须返回它。从技术上讲,我可以读取该文件并将其填充到具有适当mime类型的HttpResponse对象中,但是我想知道是否有更好的策略。 (如PHP中的fpassthru())

解决方案

这是我使用的:


$ b $
response = HttpResponse(content = test_file)
($ / $ / $ / $ response ['Content-Type'] ='application / pdf'
response ['Content-Disposition'] ='attachment; filename =%s.pdf'\
%'whatever'
return response


I need to return css files and js files according to specific logic. Clearly, static serve does not perform what I need. I have a view, whose render method uses logic to find the proper file, but then I have to return it. Technically, I can just read the file and stuff it into a HttpResponse object with the proper mime type, but I was wondering if there was a better strategy. (like fpassthru() in php)

解决方案

This is what I used:

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

这篇关于如何通过django中的视图返回静态文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆