Flask - 定期渲染没有上下文的html

时间:2014-07-04 18:01:13

标签: python html flask

我想有一个定期任务,它会呈现一个html文件并通过boto将其上传到s3。

问题在于,由于任务在端点函数之外(即由app.route修饰),因此没有Flask上下文。因此,当我的任务执行并调用render_template时,由于没有上下文而存在异常:

Traceback ........
    File "/usr/local/lib/python2.7/site-packages/flask/templating.py", line 126, in render_template
    ctx.app.update_template_context(context)
AttributeError: 'NoneType' object has no attribute 'app'

我的任务初始化是这样的,我传递了我想要定期执行的函数:

HtmlUploader.new(
    lambda: render_template('something.html', value=get_value())
).start()

有什么办法可以在app端点函数之外调用render_template吗?

1 个答案:

答案 0 :(得分:2)

使用render_template()呈现模板需要request context

您可以轻松地为批处理创建一个:

def render_with_context(template, _url='/', **kw):
    with app.test_request_context(url):
        return render_template(template, **kw)

这会为给定的URL生成“测试”请求(默认为/)。然后您可以将其用作:

HtmlUploader.new(
    lambda: render_with_context('something.html', value=get_value())
).start()