user15399439
user15399439

Reputation: 59

How to use Flask's render_template() standalone without Flask app

I'm contributing to a Flask app which uses render_template. However the app also makes use of Celery for scheduling async tasks. These tasks need to render some templates, but because they are executed by Celery asynchronously they do not have the Flask's app context, and I cannot use render_template like I would normally do inside a Flask controller (eg. @route(...)). So, how can I use render_template if I don't have a Flask context?

Upvotes: 0

Views: 1147

Answers (2)

T.M.
T.M.

Reputation: 629

In case you just need to render a template, you can just use jinja2 module which is already imported by Flask.

    >>> from jinja2 import Template
    >>> tpl = Template("I love {{ fruit }}")
    >>> print(tpl.render(fruit="apple"))
    'I love apple'

Upvotes: 0

v25
v25

Reputation: 7621

Perhaps you could achieve this by manually pushing an app context then using Flask's render_template_string function:

>>> from flask import Flask, render_template_string
>>> app = Flask(__name__)
>>> with app.app_context():
>>>     render_template_string('I love {{fruit}}', fruit='apple')
'I love apple'

Of course, instead of providing a string as the first argument to render_template_string you could open a template file, and pass fh.read()

Depending on your implementation you could probably use render_template here, although this would return a Response object.

How you deal with the return value is then up to you.

Upvotes: 1

Related Questions