如何从Django提供文本文件? [英] How do I serve a text file from Django?

查看:74
本文介绍了如何从Django提供文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个基于Django的网站,但需要提供一个简单的文本文件。通过将其放在静态目录中并绕过Django,是正确的方法吗?

I am writing a Django based website, but need to serve a a simple text file. Is the correct way to so this by putting it in the static directory and bypassing Django?

推荐答案

如果文件是静态文件(不是

If the file is static (not generated by the django app) then you can put it in the static directory.

如果此文件的内容是Django生成的,则可以将其返回到HttpResponse中,如下所示: 文本/纯文本作为模仿类型。

If the content of this file is generated by Django then you can return it in a HttpResponse with text/plain as mimetype.

content = 'any string generated by django'
return HttpResponse(content, content_type='text/plain')

您可以还可以通过设置响应的 Content-Disposition 为文件命名。

You can also give a name to the file by setting the Content-Disposition of the response.

filename = "my-file.txt"
content = 'any string generated by django'
response = HttpResponse(content, content_type='text/plain')
response['Content-Disposition'] = 'attachment; filename={0}'.format(filename)
return response

这篇关于如何从Django提供文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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