Skip to content

Instantly share code, notes, and snippets.

@SandeR2012
Created July 23, 2017 19:12
Show Gist options
  • Select an option

  • Save SandeR2012/d1d6e631c8a088d0d2d8cbd87d9b23bd to your computer and use it in GitHub Desktop.

Select an option

Save SandeR2012/d1d6e631c8a088d0d2d8cbd87d9b23bd to your computer and use it in GitHub Desktop.

Revisions

  1. SandeR2012 created this gist Jul 23, 2017.
    28 changes: 28 additions & 0 deletions flask_shell_command.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,28 @@
    @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)