Flask - 定期渲染无上下文的HTML
我想要定期执行一个任务,这个任务会生成一个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()
有没有什么办法可以在应用的端点函数外调用render_template呢?
1 个回答
3
使用 render_template()
来渲染一个模板时,需要有一个 请求上下文。
你可以很简单地为批处理过程创建一个请求上下文:
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()