django - 在 Django 中提供文件中的原始动态 html 内容?

标签 django

我可以动态地从文件生成 html 并像这样返回:

from django.http import HttpResponse
response = HttpResponse(mimetype="text/html")
content = "".join(open(filename).readlines())
response._set_content(content)
return response

但是 Django 1.5 中有更好的内置方式吗?

最佳答案

以下代码是使文件可供下载或查看的更好方法,无需流式传输(流式传输有一些缺点,例如不知道大小)。

from django.http import HttpResponse
def serve_file(filename):
    response = HttpResponse(mimetype="text/html")
    for line in open(filename):
        response.write(line)
    return response

关于django - 在 Django 中提供文件中的原始动态 html 内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19564670/

相关文章:

python - 如何覆盖夹层评论表单?

python - 将数据从 DetailView 传递到 CreateView django

django - 将 Django 项目升级到 Python3 - 迁移失败

django - 如何设置需要手动激活帐户的django-registration?

mysql - 全局单个元素的最佳数据库实践?

python - 在 Django 模型中存储电话号码的最佳方式是什么?

django - 用 bool 值注释查询集,其中一个字段等于或不等于另一个字段

python - 如何在 Django 条件注释的 then 子句中使用查询集表达式

jquery - 在 Jquery 中通过电子邮件发送 html 内容

django - 如何将上传文件保存到另一台服务器