Fix #5391 - Alembic migrations would only work for SQLite
[larjonas-mediagoblin.git] / mediagoblin / gmg_commands / shell.py
blob4d3ec241ba6eb4215d91abc1c41c3d180e51517a
1 # GNU MediaGoblin -- federated, autonomous media hosting
2 # Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU Affero General Public License for more details.
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 import code
20 from mediagoblin import mg_globals
21 from mediagoblin.gmg_commands import util as commands_util
23 from mediagoblin.tools.transition import DISABLE_GLOBALS
26 def shell_parser_setup(subparser):
27 subparser.add_argument(
28 '--ipython', help='Use ipython',
29 action="store_true")
32 if DISABLE_GLOBALS:
33 SHELL_BANNER = (
34 "GNU MediaGoblin shell!\n"
35 "----------------------\n"
36 "Available vars:\n"
37 " - app: instantiated mediagoblin application\n"
38 " - db: database session\n"
39 " - ctx: context object\n")
40 else:
41 SHELL_BANNER = (
42 "GNU MediaGoblin shell!\n"
43 "----------------------\n"
44 "Available vars:\n"
45 " - app: instantiated mediagoblin application\n"
46 " - mg_globals: mediagoblin.globals\n"
47 " - db: database instance\n"
48 " - ctx: context object\n")
50 def py_shell(**user_namespace):
51 """
52 Run a shell using normal python shell.
53 """
54 code.interact(
55 banner=SHELL_BANNER,
56 local=user_namespace)
59 def ipython_shell(**user_namespace):
60 """
61 Run a shell for the user using ipython. Return False if there is no IPython
62 """
63 try:
64 from IPython import embed
65 except:
66 return False
68 embed(
69 banner1=SHELL_BANNER,
70 user_ns=user_namespace)
71 return True
74 def shell(args):
75 """
76 Setup a shell for the user either a normal Python shell or an IPython one
77 """
78 app = commands_util.setup_app(args)
80 def run_shell(db, ctx):
81 user_namespace = {
82 'mg_globals': mg_globals,
83 'app': app,
84 'db': db,
85 "ctx": ctx}
87 if args.ipython:
88 ipython_shell(**user_namespace)
89 else:
90 # Try ipython_shell first and fall back if not available
91 if not ipython_shell(**user_namespace):
92 py_shell(**user_namespace)
94 with app.gen_context() as ctx:
95 db = ctx.db
96 run_shell(db, ctx)