Debian Codegraph @

docs/source/quick_start.rst

raw
1 .. _quick_start:
2
3 Creating Your First Pecan Application
4 =====================================
5
6 Let's create a small sample project with Pecan.
7
8 .. note::
9 This guide does not cover the installation of Pecan. If you need
10 instructions for installing Pecan, refer to :ref:`installation`.
11
12 .. _app_template:
13
14 Base Application Template
15 -------------------------
16
17 Pecan includes a basic template for starting a new project. From your
18 shell, type::
19
20 $ pecan create test_project
21
22 This example uses *test_project* as your project name, but you can replace
23 it with any valid Python package name you like.
24
25 Go ahead and change into your newly created project directory.::
26
27 $ cd test_project
28
29 You'll want to deploy it in "development mode", such that it’s
30 available on :mod:`sys.path`, yet can still be edited directly from its
31 source distribution::
32
33 $ python setup.py develop
34
35 Your new project contain these files::
36
37 $ ls
38
39 ├── MANIFEST.in
40 ├── config.py
41 ├── public
42 │   ├── css
43 │   │   └── style.css
44 │   └── images
45 ├── setup.cfg
46 ├── setup.py
47 └── test_project
48    ├── __init__.py
49    ├── app.py
50    ├── controllers
51    │   ├── __init__.py
52    │   └── root.py
53    ├── model
54    │   └── __init__.py
55    ├── templates
56    │   ├── error.html
57    │   ├── index.html
58    │   └── layout.html
59    └── tests
60    ├── __init__.py
61    ├── config.py
62    ├── test_functional.py
63    └── test_units.py
64
65 The number of files and directories may vary based on the version of
66 Pecan, but the above structure should give you an idea of what to
67 expect.
68
69 Let's review the files created by the template.
70
71 **public**
72 All your static files (like CSS, Javascript, and images) live here.
73 Pecan comes with a simple file server that serves these static files
74 as you develop.
75
76 Pecan application structure generally follows the MVC_ pattern. The
77 directories under ``test_project`` encompass your models, controllers
78 and templates.
79
80 .. _MVC: http://en.wikipedia.org/wiki/Model–view–controller
81
82 **test_project/controllers**
83 The container directory for your controller files.
84 **test_project/templates**
85 All your templates go in here.
86 **test_project/model**
87 Container for your model files.
88
89 Finally, a directory to house unit and integration tests:
90
91 **test_project/tests**
92 All of the tests for your application.
93
94 The ``test_project/app.py`` file controls how the Pecan application will be
95 created. This file must contain a :func:`setup_app` function which returns the
96 WSGI application object. Generally you will not need to modify the ``app.py``
97 file provided by the base application template unless you need to customize
98 your app in a way that cannot be accomplished using config. See
99 :ref:`python_based_config` below.
100
101 To avoid unneeded dependencies and to remain as flexible as possible,
102 Pecan doesn't impose any database or ORM (`Object Relational
103 Mapper`_). If your project will interact with a database, you can add
104 code to ``model/__init__.py`` to load database bindings from your
105 configuration file and define tables and ORM definitions.
106
107 .. _Object Relational Mapper: http://en.wikipedia.org/wiki/Object-relational_mapping
108
109 .. _running_application:
110
111 Running the Application
112 -----------------------
113
114 The base project template creates the configuration file with the
115 basic settings you need to run your Pecan application in
116 ``config.py``. This file includes the host and port to run the server
117 on, the location where your controllers and templates are stored on
118 disk, and the name of the directory containing any static files.
119
120 If you just run :command:`pecan serve`, passing ``config.py`` as the
121 configuration file, it will bring up the development server and serve
122 the app::
123
124 $ pecan serve config.py
125 Starting server in PID 000.
126 serving on 0.0.0.0:8080, view at http://127.0.0.1:8080
127
128 The location for the configuration file and the argument itself are very
129 flexible - you can pass an absolute or relative path to the file.
130
131 .. _python_based_config:
132
133 Python-Based Configuration
134 --------------------------
135 For ease of use, Pecan configuration files are pure Python--they're even saved
136 as ``.py`` files.
137
138 This is how your default (generated) configuration file should look::
139
140 # Server Specific Configurations
141 server = {
142 'port': '8080',
143 'host': '0.0.0.0'
144 }
145
146 # Pecan Application Configurations
147 app = {
148 'root': '${package}.controllers.root.RootController',
149 'modules': ['${package}'],
150 'static_root': '%(confdir)s/public',
151 'template_path': '%(confdir)s/${package}/templates',
152 'debug': True,
153 'errors': {
154 '404': '/error/404',
155 '__force_dict__': True
156 }
157 }
158
159 logging = {
160 'loggers': {
161 'root' : {'level': 'INFO', 'handlers': ['console']},
162 '${package}': {'level': 'DEBUG', 'handlers': ['console']}
163 },
164 'handlers': {
165 'console': {
166 'level': 'DEBUG',
167 'class': 'logging.StreamHandler',
168 'formatter': 'simple'
169 }
170 },
171 'formatters': {
172 'simple': {
173 'format': ('%(asctime)s %(levelname)-5.5s [%(name)s]'
174 '[%(threadName)s] %(message)s')
175 }
176 }
177 }
178
179 # Custom Configurations must be in Python dictionary format::
180 #
181 # foo = {'bar':'baz'}
182 #
183 # All configurations are accessible at::
184 # pecan.conf
185
186 You can also add your own configuration as Python dictionaries.
187
188 There's a lot to cover here, so we'll come back to configuration files in
189 a later chapter (:ref:`Configuration`).
190
191
192 The Application Root
193 --------------------
194
195 The **Root Controller** is the entry point for your application. You
196 can think of it as being analogous to your application's root URL path
197 (in our case, ``http://localhost:8080/``).
198
199 This is how it looks in the project template
200 (``test_project.controllers.root.RootController``)::
201
202 from pecan import expose
203 from webob.exc import status_map
204
205
206 class RootController(object):
207
208 @expose(generic=True, template='index.html')
209 def index(self):
210 return dict()
211
212 @index.when(method='POST')
213 def index_post(self, q):
214 redirect('https://pecan.readthedocs.io/en/latest/search.html?q=%s' % q)
215
216 @expose('error.html')
217 def error(self, status):
218 try:
219 status = int(status)
220 except ValueError:
221 status = 0
222 message = getattr(status_map.get(status), 'explanation', '')
223 return dict(status=status, message=message)
224
225
226 You can specify additional classes and methods if you need to do so, but for
227 now, let's examine the sample project, controller by controller::
228
229 @expose(generic=True, template='index.html')
230 def index(self):
231 return dict()
232
233 The :func:`index` method is marked as *publicly available* via the
234 :func:`~pecan.decorators.expose` decorator (which in turn uses the
235 ``index.html`` template) at the root of the application
236 (http://127.0.0.1:8080/), so any HTTP ``GET`` that hits the root of your
237 application (``/``) will be routed to this method.
238
239 Notice that the :func:`index` method returns a Python dictionary. This dictionary
240 is used as a namespace to render the specified template (``index.html``) into
241 HTML, and is the primary mechanism by which data is passed from controller to
242 template.
243
244 ::
245
246 @index.when(method='POST')
247 def index_post(self, q):
248 redirect('https://pecan.readthedocs.io/en/latest/search.html?q=%s' % q)
249
250 The :func:`index_post` method receives one HTTP ``POST`` argument (``q``). Because
251 the argument ``method`` to :func:`@index.when` has been set to ``'POST'``, any
252 HTTP ``POST`` to the application root (in the example project, a form
253 submission) will be routed to this method.
254
255 ::
256
257 @expose('error.html')
258 def error(self, status):
259 try:
260 status = int(status)
261 except ValueError:
262 status = 0
263 message = getattr(status_map.get(status), 'explanation', '')
264 return dict(status=status, message=message)
265
266 Finally, we have the :func:`error` method, which allows the application to display
267 custom pages for certain HTTP errors (``404``, etc...).
268
269 Running the Tests For Your Application
270 --------------------------------------
271
272 Your application comes with a few example tests that you can run, replace, and
273 add to. To run them::
274
275 $ pip install tox && tox -e py
276
277 The tests themselves can be found in the ``tests`` module in your project.
278
279 Deploying to a Web Server
280 -------------------------
281
282 Ready to deploy your new Pecan app? Take a look at :ref:`deployment`.