Debian Codegraph @

pecan/commands/shell.py

raw
1 """
2 Shell command for Pecan.
3 """
4 from pecan.commands import BaseCommand
5 try:
6 from webtest import TestApp
7 except ImportError:
8 TestApp = None
9 from warnings import warn
10 import sys
11
12
13 class NativePythonShell(object):
14 """
15 Open an interactive python shell with the Pecan app loaded.
16 """
17
18 @classmethod
19 def invoke(cls, ns, banner): # pragma: nocover
20 """
21 :param ns: local namespace
22 :param banner: interactive shell startup banner
23
24 Embed an interactive native python shell.
25 """
26 import code
27 py_prefix = sys.platform.startswith('java') and 'J' or 'P'
28 shell_banner = 'Pecan Interactive Shell\n%sython %s\n\n' % \
29 (py_prefix, sys.version)
30 shell = code.InteractiveConsole(locals=ns)
31 try:
32 import readline # noqa
33 except ImportError:
34 pass
35 shell.interact(shell_banner + banner)
36
37
38 class IPythonShell(object):
39 """
40 Open an interactive ipython shell with the Pecan app loaded.
41 """
42
43 @classmethod
44 def invoke(cls, ns, banner): # pragma: nocover
45 """
46 :param ns: local namespace
47 :param banner: interactive shell startup banner
48
49 Embed an interactive ipython shell.
50 Try the InteractiveShellEmbed API first, fall back on
51 IPShellEmbed for older IPython versions.
52 """
53 try:
54 from IPython.frontend.terminal.embed import (
55 InteractiveShellEmbed
56 )
57 # try and load their default profile
58 from IPython.frontend.terminal.ipapp import (
59 load_default_config
60 )
61 config = load_default_config()
62 shell = InteractiveShellEmbed(config=config, banner2=banner)
63 shell(local_ns=ns)
64 except ImportError:
65 # Support for the IPython <= 0.10 shell API
66 from IPython.Shell import IPShellEmbed
67 shell = IPShellEmbed(argv=[])
68 shell.set_banner(shell.IP.BANNER + '\n\n' + banner)
69 shell(local_ns=ns, global_ns={})
70
71
72 class BPythonShell(object):
73 """
74 Open an interactive bpython shell with the Pecan app loaded.
75 """
76
77 @classmethod
78 def invoke(cls, ns, banner): # pragma: nocover
79 """
80 :param ns: local namespace
81 :param banner: interactive shell startup banner
82
83 Embed an interactive bpython shell.
84 """
85 from bpython import embed
86 embed(ns, ['-i'], banner)
87
88
89 class ShellCommand(BaseCommand):
90 """
91 Open an interactive shell with the Pecan app loaded.
92 Attempt to invoke the specified python shell flavor
93 (ipython, bpython, etc.). Fall back on the native
94 python shell if the requested flavor variance is not
95 installed.
96 """
97
98 SHELLS = {
99 'python': NativePythonShell,
100 'ipython': IPythonShell,
101 'bpython': BPythonShell,
102 }
103
104 arguments = BaseCommand.arguments + ({
105 'name': ['--shell', '-s'],
106 'help': 'which Python shell to use',
107 'choices': SHELLS.keys(),
108 'default': 'python'
109 },)
110
111 def run(self, args):
112 """
113 Load the pecan app, prepare the locals, sets the
114 banner, and invokes the python shell.
115 """
116 super(ShellCommand, self).run(args)
117
118 # load the application
119 app = self.load_app()
120
121 # prepare the locals
122 locs = dict(__name__='pecan-admin')
123 locs['wsgiapp'] = app
124 if TestApp:
125 locs['app'] = TestApp(app)
126
127 model = self.load_model(app.config)
128 if model:
129 locs['model'] = model
130
131 # insert the pecan locals
132 from pecan import abort, conf, redirect, request, response
133 locs['abort'] = abort
134 locs['conf'] = conf
135 locs['redirect'] = redirect
136 locs['request'] = request
137 locs['response'] = response
138
139 # prepare the banner
140 banner = ' The following objects are available:\n'
141 banner += ' %-10s - This project\'s WSGI App instance\n' % 'wsgiapp'
142 banner += ' %-10s - The current configuration\n' % 'conf'
143 if TestApp:
144 banner += ' %-10s - webtest.TestApp wrapped around wsgiapp\n' % 'app' # noqa
145 if model:
146 model_name = getattr(
147 model,
148 '__module__',
149 getattr(model, '__name__', 'model')
150 )
151 banner += ' %-10s - Models from %s\n' % ('model', model_name)
152
153 self.invoke_shell(locs, banner)
154
155 def invoke_shell(self, locs, banner):
156 """
157 Invokes the appropriate flavor of the python shell.
158 Falls back on the native python shell if the requested
159 flavor (ipython, bpython,etc) is not installed.
160 """
161 shell = self.SHELLS[self.args.shell]
162 try:
163 shell().invoke(locs, banner)
164 except ImportError as e:
165 warn((
166 "%s is not installed, `%s`, "
167 "falling back to native shell") % (self.args.shell, e),
168 RuntimeWarning
169 )
170 if shell == NativePythonShell:
171 raise
172 NativePythonShell().invoke(locs, banner)
173
174 def load_model(self, config):
175 """
176 Load the model extension module
177 """
178 for package_name in getattr(config.app, 'modules', []):
179 module = __import__(package_name, fromlist=['model'])
180 if hasattr(module, 'model'):
181 return module.model
182 return None