Skip to content
thesarfo

Note

Flask App Context

Fixing the application-context error when running database operations from the Python terminal in a Flask app.

views 0

These Flask notes were taken while building a companion blog project, so the code snippets and examples are relative to that project (referred to below as flasky/shadys-blog).

If you try to perform a database operation or any operation on the python terminal in your flask application and you get an app context error, you can use the below code to fix it.

from flasky import app
from flasky.models import Post
from flask import current_app
# Get the application context
ctx = app.app_context()
ctx.push()
# Access the current application
current_app.app_context().push()
# Perform your database operations
posts = Post.query.all() #just an example
# Rest of your code
# Clean up the application context
ctx.pop()