periodically rendering html without context

I would like to have a periodic task which renders an html file and uploads it to s3 via boto.

The problem with this is that since the task is outside of an endpoint function (ie decorated by app.route), there is no Flask context. So, when my task executes and render_template is called, there is an exception due to there being no context:

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'

My task is initialized something like this, where I pass in the function I want to execute periodically:

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

Is there any way I can call render_template outside of an app endpoint function?


Rendering a template with render_template() requires a request context.

You can easily create one for just the batch process:

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

This produces a 'test' request for a given URL (defaults to / ). You can then use this as:

HtmlUploader.new(
    lambda: render_with_context('something.html', value=get_value())
).start()
链接地址: http://www.djcxy.com/p/71892.html

上一篇: 如何使用Flask的渲染

下一篇: 定期呈现没有上下文的HTML