Skip to content

Instantly share code, notes, and snippets.

@SandeR2012
Created July 23, 2017 19:12
Show Gist options
  • Save SandeR2012/d1d6e631c8a088d0d2d8cbd87d9b23bd to your computer and use it in GitHub Desktop.
Save SandeR2012/d1d6e631c8a088d0d2d8cbd87d9b23bd to your computer and use it in GitHub Desktop.
@app.cli.command('shell', short_help='Runs a shell in the app context.')
def shell_command():
"""Runs an interactive Python shell in the context of a given
Flask application. The application will populate the default
namespace of this shell according to it's configuration.
This is useful for executing small snippets of management code
without having to manually configuring the application.
"""
import code
from flask.globals import _app_ctx_stack
app = _app_ctx_stack.top.app
banner = 'Python %s on %s\nApp: %s%s\nInstance: %s' % (
sys.version,
sys.platform,
app.import_name,
app.debug and ' [debug]' or '',
app.instance_path,
)
ctx = {}
ctx.update(app.make_shell_context())
try:
from IPython import embed
embed(banner1=banner, user_ns=ctx)
except ImportError:
code.interact(banner=banner, local=ctx)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment