I am currently using Python Flask and Jinja2. I have a table with some message. I want to basically have a button on the menu with the number of messages that a user has.
I've used this to make my sidebar global so it can appear on multiple pages: app.jinja_env.globals.update(...)
This is the code I've used to get the number of messages: def message_notification(): c.execute("SELECT count(*) FROM messages WHERE read = 0 AND receiver = ?",(session['username'],)) msgnotifcation = c.fetchone() return msgnotifcation[0]
However I am getting this error: RuntimeError: Working outside of request context.
Is there any other way to do this as I figured out that the problem is to do with the session['username'] bit.
You need to move this code so that it executes before the template starts to render, ie it will be inside the request context.
Flask provides the context_processor decorator to achieve this. http://flask.pocoo.org/docs/0.12/templating/#context-processors The values returned will be available in all your templates as though they had been returned as any other context item from a view.
@app.context_processor
def message_count():
value = ...your sql...
return dict(message_count=value)
Then in your views you can use:
{{ message_count }}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.