Debian Codegraph @

docs/source/commands.rst

raw
1 .. _commands:
2
3 Command Line Pecan
4 ==================
5
6 Any Pecan application can be controlled and inspected from the command
7 line using the built-in :command:`pecan` command. The usage examples
8 of :command:`pecan` in this document are intended to be invoked from
9 your project's root directory.
10
11 Serving a Pecan App For Development
12 -----------------------------------
13
14 Pecan comes bundled with a lightweight WSGI development server based on
15 Python's :py:mod:`wsgiref.simple_server` module.
16
17 Serving your Pecan app is as simple as invoking the ``pecan serve`` command::
18
19 $ pecan serve config.py
20 Starting server in PID 000.
21 serving on 0.0.0.0:8080, view at http://127.0.0.1:8080
22
23 and then visiting it in your browser.
24
25 The server ``host`` and ``port`` in your configuration file can be changed as
26 described in :ref:`server_configuration`.
27
28 .. include:: reload.rst
29 :start-after: #reload
30
31 The Interactive Shell
32 ---------------------
33
34 Pecan applications also come with an interactive Python shell which can be used
35 to execute expressions in an environment very similar to the one your
36 application runs in. To invoke an interactive shell, use the ``pecan shell``
37 command::
38
39 $ pecan shell config.py
40 Pecan Interactive Shell
41 Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
42 [GCC 4.2.1 (Based on Apple Inc. build 5658)
43
44 The following objects are available:
45 wsgiapp - This project's WSGI App instance
46 conf - The current configuration
47 app - webtest.TestApp wrapped around wsgiapp
48
49 >>> conf
50 Config({
51 'app': Config({
52 'root': 'myapp.controllers.root.RootController',
53 'modules': ['myapp'],
54 'static_root': '/Users/somebody/myapp/public',
55 'template_path': '/Users/somebody/myapp/project/templates',
56 'errors': {'404': '/error/404'},
57 'debug': True
58 }),
59 'server': Config({
60 'host': '0.0.0.0',
61 'port': '8080'
62 })
63 })
64 >>> app
65 <webtest.app.TestApp object at 0x101a830>
66 >>> app.get('/')
67 <200 OK text/html body='<html>\n ...\n\n'/936>
68
69 Press ``Ctrl-D`` to exit the interactive shell (or ``Ctrl-Z`` on Windows).
70
71 Using an Alternative Shell
72 ++++++++++++++++++++++++++
73
74 ``pecan shell`` has optional support for the `IPython <http://ipython.org/>`_
75 and `bpython <http://bpython-interpreter.org/>`_ alternative shells, each of
76 which can be specified with the ``--shell`` flag (or its abbreviated alias,
77 ``-s``), e.g.,
78
79 ::
80
81 $ pecan shell --shell=ipython config.py
82 $ pecan shell -s bpython config.py
83
84
85 .. _env_config:
86
87 Configuration from an environment variable
88 ------------------------------------------
89
90 In all the examples shown, you will see that the :command:`pecan` commands
91 accepted a file path to the configuration file. An alternative to this is to
92 specify the configuration file in an environment variable (:envvar:`PECAN_CONFIG`).
93
94 This is completely optional; if a file path is passed in explicitly, Pecan will
95 honor that before looking for an environment variable.
96
97 For example, to serve a Pecan application, a variable could be exported and
98 subsequently be re-used when no path is passed in.
99
100 ::
101
102 $ export PECAN_CONFIG=/path/to/app/config.py
103 $ pecan serve
104 Starting server in PID 000.
105 serving on 0.0.0.0:8080, view at http://127.0.0.1:8080
106
107 Note that the path needs to reference a valid pecan configuration file,
108 otherwise the command will error out with a message indicating that
109 the path is invalid (for example, if a directory is passed in).
110
111 If :envvar:`PECAN_CONFIG` is not set and no configuration is passed in, the command
112 will error out because it will not be able to locate a configuration file.
113
114
115 Extending ``pecan`` with Custom Commands
116 ----------------------------------------
117
118 While the commands packaged with Pecan are useful, the real utility of its
119 command line toolset lies in its extensibility. It's convenient to be able to
120 write a Python script that can work "in a Pecan environment" with access to
121 things like your application's parsed configuration file or a simulated
122 instance of your application itself (like the one provided in the ``pecan
123 shell`` command).
124
125 Writing a Custom Pecan Command
126 ++++++++++++++++++++++++++++++
127
128 As an example, let's create a command that can be used to issue a simulated
129 HTTP GET to your application and print the result. Its invocation from the
130 command line might look something like this::
131
132 $ pecan wget config.py /path/to/some/resource
133
134 Let's say you have a distribution with a package in it named ``myapp``, and
135 that within this package is a ``wget.py`` module::
136
137 # myapp/myapp/wget.py
138 import pecan
139 from webtest import TestApp
140
141 class GetCommand(pecan.commands.BaseCommand):
142 '''
143 Issues a (simulated) HTTP GET and returns the request body.
144 '''
145
146 arguments = pecan.commands.BaseCommand.arguments + ({
147 'name': 'path',
148 'help': 'the URI path of the resource to request'
149 },)
150
151 def run(self, args):
152 super(GetCommand, self).run(args)
153 app = TestApp(self.load_app())
154 print app.get(args.path).body
155
156 Let's analyze this piece-by-piece.
157
158 Overriding the ``run`` Method
159 ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
160
161 First, we're subclassing :class:`~pecan.commands.base.BaseCommand` and extending
162 the :func:`~pecan.commands.base.BaseCommandParent.run` method to:
163
164 * Load a Pecan application - :func:`~pecan.core.load_app`
165 * Wrap it in a fake WGSI environment - :class:`~webtest.app.TestApp`
166 * Issue an HTTP GET request against it - :meth:`~webtest.app.TestApp.get`
167
168 Defining Custom Arguments
169 ,,,,,,,,,,,,,,,,,,,,,,,,,
170
171 The :attr:`arguments` class attribute is used to define command line arguments
172 specific to your custom command. You'll notice in this example that we're
173 *adding* to the arguments list provided by :class:`~pecan.commands.base.BaseCommand`
174 (which already provides an argument for the ``config_file``), rather
175 than overriding it entirely.
176
177 The format of the :attr:`arguments` class attribute is a :class:`tuple` of
178 dictionaries, with each dictionary representing an argument definition in the
179 same format accepted by Python's :py:mod:`argparse` module (more specifically,
180 :meth:`~argparse.ArgumentParser.add_argument`). By providing a list of
181 arguments in this format, the :command:`pecan` command can include your custom
182 commands in the help and usage output it provides.
183
184 ::
185
186 $ pecan -h
187 usage: pecan [-h] command ...
188
189 positional arguments:
190 command
191 wget Issues a (simulated) HTTP GET and returns the request body
192 serve Open an interactive shell with the Pecan app loaded
193 ...
194
195 $ pecan wget -h
196 usage: pecan wget [-h] config_file path
197 $ pecan wget config.py /path/to/some/resource
198
199 Additionally, you'll notice that the first line of the docstring from
200 :class:`GetCommand` -- ``Issues a (simulated) HTTP GET and returns the
201 request body`` -- is automatically used to describe the :command:`wget`
202 command in the output for ``$ pecan -h``. Following this convention
203 allows you to easily integrate a summary for your command into the
204 Pecan command line tool.
205
206 Registering a Custom Command
207 ++++++++++++++++++++++++++++
208
209 Now that you've written your custom command, you’ll need to tell your
210 distribution’s ``setup.py`` about its existence and reinstall. Within your
211 distribution’s ``setup.py`` file, you'll find a call to :func:`~setuptools.setup`.
212
213 ::
214
215 # myapp/setup.py
216 ...
217 setup(
218 name='myapp',
219 version='0.1',
220 author='Joe Somebody',
221 ...
222 )
223
224 Assuming it doesn't exist already, we'll add the ``entry_points`` argument
225 to the :func:`~setuptools.setup` call, and define a ``[pecan.command]`` definition for your custom
226 command::
227
228
229 # myapp/setup.py
230 ...
231 setup(
232 name='myapp',
233 version='0.1',
234 author='Joe Somebody',
235 ...
236 entry_points="""
237 [pecan.command]
238 wget = myapp.wget:GetCommand
239 """
240 )
241
242 Once you've done this, reinstall your project in development to register the
243 new entry point.
244
245 ::
246
247 $ python setup.py develop
248
249 Then give it a try.
250
251 ::
252
253 $ pecan wget config.py /path/to/some/resource