Navigation

One of the reasons everybody loves Python is the interactive shell. It
basically allows you to execute Python commands in real time and
immediately get results back. Flask itself does not come with an
interactive shell, because it does not require any specific setup upfront,
just import your application and start playing around.

There are however some handy helpers to make playing around in the shell a
more pleasant experience. The main issue with interactive console
sessions is that you’re not triggering a request like a browser does which
means that g, request and others are not
available. But the code you want to test might depend on them, so what
can you do?

This is where some helper functions come in handy. Keep in mind however
that these functions are not only there for interactive shell usage, but
also for unittesting and other situations that require a faked request
context.

Generally it’s recommended that you read the The Request Context
chapter of the documentation first.

Starting with Flask 0.11 the recommended way to work with the shell is the
flaskshell command which does a lot of this automatically for you.
For instance the shell is automatically initialized with a loaded
application context.

By just creating a request context, you still don’t have run the code that
is normally run before a request. This might result in your database
being unavailable if you are connecting to the database in a
before-request callback or the current user not being stored on the
g object etc.

The functions registered as teardown_request() are
automatically called when the context is popped. So this is the perfect
place to automatically tear down resources that were needed by the request
context (such as database connections).

If you like the idea of experimenting in a shell, create yourself a module
with stuff you want to star import into your interactive session. There
you could also define some more helper methods for common things such as
initializing the database, dropping tables etc.