33

我是 Django 的新手,我很确定我已经阅读或听说过一种方法来做到这一点,但我在任何地方都找不到。

我不想将渲染的输出从模板发送到浏览器,而是想创建一个 html 文件,然后无需每次都经过渲染过程即可提供该文件。我正在一个与我们的主网站服务器分开的系统上进行开发,我需要定期为我们的用户提供我的数据快照,而不让他们访问开发系统。

我的直觉说我应该能够以某种方式将响应重定向到文件,但我没有在文档或此处的其他帖子中看到它。

4

2 回答 2

34

您可以利用 Django 的模板加载器来呈现您的模板,包括您传递给它的任何上下文,作为字符串,然后将其保存到文件系统。如果您需要将该文件保存在外部系统上,例如 Amazon S3,您可以使用Boto库。

这是一个如何将视图呈现到文件的示例,使用可选的查询字符串参数作为触发器......

from django.shortcuts import render
from django.template.loader import render_to_string

def my_view(request):
    as_file = request.GET.get('as_file')
    context = {'some_key': 'some_value'}

    if as_file:
        content = render_to_string('your-template.html', context)                
        with open('path/to/your-template-static.html', 'w') as static_file:
            static_file.write(content)

    return render('your-template.html', context)
于 2014-03-04T03:52:33.600 回答
6

django-bakery是一个完善的“一组帮助程序,用于将您的 Django 站点烘焙为平面文件”。

于 2016-07-08T16:05:13.360 回答