Reputation: 162
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.
Upvotes: 1
Views: 1104
Reputation: 934
You need to move this code so that it executes before the template starts to render, i.e. 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 }}
Upvotes: 2