python - how to render template in flask without using request context -
so there's flask app i'm working on project , need run in loop @ timed variables check status of variables , give output accordingly. however, problem have need render template in flask before loop restarts. in changelog on http://flask.pocoo.org/ it's indicated it's possible render templates without using request context haven't seen real examples of this. there way render templates in flask without having use request context without getting errors? can given appreciated.
update: here's code i'm working with
from flask import flask, render_template, request, flash, redirect, url_for import flask import time flask.ext.assets import environment, bundle flask_wtf import form wtforms import textfield, textareafield, submitfield wtforms.validators import inputrequired csrf_enabled = true app = flask(__name__) app.secret_key = 'development key' app = flask.flask('my app') assets = environment(app) assets.url = app.static_url_path scss = bundle('scss/app.scss', filters='scss', output='css/app.css') assets.register('app_scss', scss) @app.route('/') def server_1(): r=1 g=2 b=3 i=g if == g: app.app_context(): print "loading template..." rendered = flask.render_template('server_1.html', green=true) print "success! template loaded green server status..." time.sleep(5) if __name__ == '__main__': app.run(port=5000, debug=true)
you can binding application current application. can use render_template()
render template template directory, or render_template_string()
render directly template stored in string:
import flask app = flask.flask('my app') app.app_context(): context = {'name': 'bob', 'age': 22} rendered = flask.render_template('index.html', **context) app.app_context(): template = '{{ name }} {{ age }} years old.' context = {'name': 'bob', 'age': 22} rendered = flask.render_template_string(template, **context)
alternatively bypass flask , go directly jinja2:
import jinja2 template = jinja2.template('{{ name }} {{ age }} years old.') rendered = template.render(name='ginger', age=10)
update
it appears might wanting stream content requesting client. if write generator. might work:
import time flask import flask, response, render_template_string flask import stream_with_context app = flask(__name__) @app.route("/") def server_1(): def generate_output(): age = 0 template = '<p>{{ name }} {{ age }} seconds old.</p>' context = {'name': 'bob'} while true: context['age'] = age yield render_template_string(template, **context) time.sleep(5) age += 5 return response(stream_with_context(generate_output())) app.run()
here documentation on streaming flask.
Comments
Post a Comment