Created
December 9, 2020 09:23
-
-
Save sh4nks/c5298b9d23ef0d5f51df658ab56531be to your computer and use it in GitHub Desktop.
flask shell with ipython
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_version(ctx, param, value): | |
if not value or ctx.resilient_parsing: | |
return | |
message = ( | |
"<project> %(version)s using Flask %(flask_version)s on " | |
"Python %(python_version)s" | |
) | |
click.echo( | |
message | |
% { | |
"version": <project_version>, | |
"flask_version": flask_version, | |
"python_version": sys.version.split("\n")[0], | |
}, | |
color=ctx.color, | |
) | |
ctx.exit() | |
@click.group(cls=FlaskGroup, create_app=create_app, add_version_option=False) | |
@click.version_option() | |
@click.option( | |
"--version", | |
expose_value=False, | |
callback=get_version, | |
is_flag=True, | |
is_eager=True, | |
help="Show the version and exit.", | |
) | |
def main(args=None): | |
"""Command line interface for the <my project>""" | |
@main.command("shell", short_help="Runs a shell in the app context.") | |
def shell_command(): | |
"""Run an interactive Python shell in the context of a given | |
Flask application. The application will populate the default | |
namespace of this shell according to its configuration. | |
This is useful for executing small snippets of management code | |
without having to manually configuring the application. | |
This code snippet is taken from Flask's cli module and modified to | |
run IPython and falls back to the normal shell if IPython is not | |
available. | |
""" | |
import code | |
app = create_app() | |
ctx = {"db": db} | |
banner = "Python %s on %s\nApp: %s [%s]\nContext: %s\nInstance: %s" % ( | |
sys.version, | |
sys.platform, | |
app.import_name, | |
app.env, | |
list(ctx.keys()), | |
app.instance_path, | |
) | |
# Support the regular Python interpreter startup script if someone | |
# is using it. | |
startup = os.environ.get("PYTHONSTARTUP") | |
if startup and os.path.isfile(startup): | |
with open(startup, "r") as f: | |
eval(compile(f.read(), startup, "exec"), ctx) | |
ctx.update(app.make_shell_context()) | |
try: | |
import IPython | |
from traitlets.config import get_config | |
c = get_config() | |
c.InteractiveShellEmbed.colors = "Linux" # This makes the prompt to use colors again | |
IPython.embed(config=c, 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