Michael Merickel
2018-10-16 8eed333343e4e9e7f11f3aee67299030d6bf2783
commit | author | age
837916 1 .. _project_narr:
CM 2
fd5ae9 3 Creating a :app:`Pyramid` Project
609a99 4 =================================
54f2bb 5
a54e4c 6 As we saw in :ref:`firstapp_chapter`, it's possible to create a :app:`Pyramid`
SP 7 application completely manually.  However, it's usually more convenient to use
6b6d0e 8 our :term:`cookiecutter` to generate a basic :app:`Pyramid` :term:`project`.
41e3bf 9
3f695c 10 A project is a directory that contains at least one Python :term:`package`.
6b6d0e 11 You'll use the :app:`Pyramid` cookiecutter to create a project, and you'll
SM 12 create your application logic within a package that lives inside the project.
13 Even if your application is extremely simple, it is useful to place code that
14 drives the application within a package, because (1) a package is more easily
15 extended with new code, and (2) an application that lives inside a package can
16 also be distributed more easily than one which does not live within a package.
9ec2d6 17
6b6d0e 18 The Pylons Project provides a :app:`Pyramid` cookiecutter that you can use to
SM 19 generate a project.  Our cookiecutter allows several configuration options
f2520e 20 to generate the type of application you're trying to construct.
a119be 21
6b6d0e 22 This cookiecutter is rendered using the ``cookiecutter`` command that you may install.
e2cda9 23
SP 24 .. seealso::
25
e1b26e 26     See also `Cookiecutter Installation <https://cookiecutter.readthedocs.io/en/latest/installation.html>`_.
e2cda9 27
9ec2d6 28
CM 29 .. index::
e2cda9 30    single: cookiecutters
28e688 31    single: pyramid-cookiecutter-starter
9ec2d6 32
e2cda9 33 .. _additional_cookiecutters:
9ec2d6 34
e2cda9 35 :app:`Pyramid` cookiecutters
SP 36 ----------------------------
37
f2520e 38 The Pyramid cookiecutter released under the Pylons Project offers the following configuration options:
e2cda9 39
f2520e 40 - templating libraries (:term:`Jinja2`, :term:`Chameleon`, or :term:`Mako`)
e1b26e 41
f2520e 42 - the persistence mechanism (no persistence mechanism, :term:`SQLAlchemy` with SQLite, or :term:`ZODB`)
e1b26e 43
f2520e 44 - the mechanism of mapping URLs to code (:term:`URL dispatch` or :term:`traversal`)
e1b26e 45
28e688 46 * `pyramid-cookiecutter-starter <https://github.com/Pylons/pyramid-cookiecutter-starter>`_
e2cda9 47
f2520e 48 All configuration options offer a choice of templating language.
9ec2d6 49
f2520e 50 The configuration of mapping URLs to code (routing) depends on the backend option selected, with additional variations as follows.
SM 51
52 ``none``
6b6d0e 53     :term:`URL dispatch` for routing
9ec2d6 54
f2520e 55 ``sqlalchemy``
SM 56     SQLite for persistent storage, :term:`SQLAlchemy` for an ORM, :term:`URL dispatch` for routing, and :term:`Alembic` for database migrations
9ec2d6 57
f2520e 58 ``zodb``
6b6d0e 59     :term:`ZODB` for persistent storage and :term:`traversal` for routing
8afd28 60
5ff3d2 61
8c56ae 62 .. index::
c5f24b 63    single: creating a project
CM 64    single: project
e1b26e 65    single: cookiecutter
8c56ae 66
e60df4 67 .. _creating_a_project:
CM 68
0bc787 69 Creating the Project
CM 70 --------------------
5ff3d2 71
a54e4c 72 In :ref:`installing_chapter`, you created a virtual Python environment via the
e1b26e 73 ``venv`` command. We called the virtual environment directory
SP 74 ``env`` and set an environment variable ``VENV`` to its path.
545654 75
7ed8e2 76 We assume that you :ref:`previously installed cookiecutter <cookiecutters>`, following its installation instructions.
e1b26e 77
6b6d0e 78 When we invoke ``cookiecutter``, it will create a directory that represents our project.
e1b26e 79
7ed8e2 80 We assume our current working directory is the value of ``VENV``.
0dd16d 81
7ed8e2 82 On all platforms, generate a project using cookiecutter.
54f2bb 83
d4177a 84 .. code-block:: bash
189c6e 85
0080e9 86     cookiecutter gh:Pylons/pyramid-cookiecutter-starter --checkout 1.10-branch
54f2bb 87
e1b26e 88 If prompted for the first item, accept the default ``yes`` by hitting return.
SP 89
2cd381 90 .. code-block:: text
SP 91
28e688 92     You've cloned ~/.cookiecutters/pyramid-cookiecutter-starter before.
2cd381 93     Is it okay to delete and re-clone it? [yes]: yes
SP 94     project_name [Pyramid Scaffold]: myproject
6ff6fa 95     repo_name [myproject]: myproject
2cd381 96     Select template_language:
SP 97     1 - jinja2
98     2 - chameleon
6204d8 99     3 - mako
6b6d0e 100     Choose from 1, 2, 3 [1]: 1
SM 101     Select backend:
102     1 - none
103     2 - sqlalchemy
104     3 - zodb
6204d8 105     Choose from 1, 2, 3 [1]: 1
e1b26e 106
SP 107 We then run through the following commands.
108
5af300 109 On Unix:
e1b26e 110
SP 111 .. code-block:: bash
112
113     # Reset our environment variable for a new virtual environment.
f07408 114     export VENV=~/env/myproject/env
e1b26e 115     # Change directory into your newly created project.
f07408 116     cd myproject
e1b26e 117     # Create a new virtual environment...
f07408 118     python3 -m venv $VENV
e1b26e 119     # ...where we upgrade packaging tools.
f07408 120     env/bin/pip install --upgrade pip setuptools
e1b26e 121
SP 122 Or on Windows:
123
124 .. code-block:: doscon
125
126     # Reset our environment variable for a new virtual environment.
f07408 127     set VENV=c:\env\myproject\env
e1b26e 128     # Change directory into your newly created project.
f07408 129     cd myproject
e1b26e 130     # Create a new virtual environment...
f07408 131     python -m venv %VENV%
e1b26e 132     # ...where we upgrade packaging tools.
f07408 133     %VENV%\Scripts\pip install --upgrade pip setuptools
e1b26e 134
SP 135 As a result of invoking the ``cookiecutter`` command, a directory named
136 ``myproject`` is created.  That directory is a :term:`project` directory. The
a54e4c 137 ``setup.py`` file in that directory can be used to distribute your application,
SP 138 or install your application for deployment or development.
9ec2d6 139
f21b2b 140 An ``.ini`` file named ``development.ini`` will be created in the project
a54e4c 141 directory.  You will use this ``.ini`` file to configure a server, to run your
SP 142 application, and to debug your application.  It contains configuration that
143 enables an interactive debugger and settings optimized for development.
43ab04 144
cfb2b5 145 Another ``.ini`` file named ``production.ini`` will also be created in the
f23bec 146 project directory.  It contains configuration that disables any interactive
cfb2b5 147 debugger (to prevent inappropriate access and disclosure), and turns off a
CM 148 number of debugging settings.  You can use this file to put your application
149 into production.
54f2bb 150
e1b26e 151 The ``myproject`` project directory contains an additional subdirectory named
a54e4c 152 ``myproject`` (note the case difference) representing a Python :term:`package`
SP 153 which holds very simple :app:`Pyramid` sample code.  This is where you'll edit
154 your application's Python code and templates.
54f2bb 155
e1b26e 156 We created this project in a directory next to its virtual environment directory.
d67566 157 However, note that this is not mandatory. The project directory can go more or
SP 158 less anywhere on your filesystem. You don't need to put it in a special "web
e1b26e 159 server" directory. You could put it within a virtual environment
d67566 160 directory. The author uses Linux mainly, and tends to put project directories
SP 161 which he creates within his ``~/projects`` directory. On Windows, it's a good
162 idea to put project directories within a directory that contains no space
163 characters, so it's wise to *avoid* a path that contains, i.e., ``My
164 Documents``. As a result, the author, when he uses Windows, just puts his
165 projects in ``C:\projects``.
545654 166
1a76ed 167 .. warning::
7b5544 168
e1b26e 169    You'll need to avoid using ``cookiecutter`` to create a project with the same
be8e3a 170    name as a Python standard library component. In particular, this means you
a54e4c 171    should avoid using the names ``site`` or ``test``, both of which conflict
SP 172    with Python standard library packages.  You should also avoid using the name
173    ``pyramid``, which will conflict with Pyramid itself.
7b5544 174
8c56ae 175 .. index::
9ec2d6 176    single: setup.py develop
CM 177    single: development install
2ff0c8 178
54f2bb 179 Installing your Newly Created Project for Development
CM 180 -----------------------------------------------------
181
429029 182 To install a newly created project for development, you should ``cd`` to the
CM 183 newly created project directory and use the Python interpreter from the
d67566 184 :term:`virtual environment` you created during :ref:`installing_chapter` to
SP 185 invoke the command ``pip install -e .``, which installs the project in
186 development mode (``-e`` is for "editable") into the current directory (``.``).
429029 187
e1b26e 188 The file named ``setup.py`` will be in the root of the cookiecutter-generated
a54e4c 189 project directory.  The ``python`` you're invoking should be the one that lives
SP 190 in the ``bin`` (or ``Scripts`` on Windows) directory of your virtual Python
191 environment.  Your terminal's current working directory *must* be the newly
192 created project directory.
d0ec94 193
5af300 194 On Unix:
54f2bb 195
d4177a 196 .. code-block:: bash
8f7262 197
f07408 198     $VENV/bin/pip install -e .
8f7262 199
d0ec94 200 Or on Windows:
189c6e 201
a651b3 202 .. code-block:: doscon
189c6e 203
f07408 204     %VENV%\Scripts\pip install -e .
d0ec94 205
5af300 206 Elided output from a run of this command on Unix is shown below:
d0ec94 207
d4177a 208 .. code-block:: bash
d0ec94 209
f07408 210     Running setup.py develop for myproject
e1b26e 211     Successfully installed Jinja2-2.8 Mako-1.0.6 MarkupSafe-0.23 \
SP 212     PasteDeploy-1.5.2 Pygments-2.1.3 WebOb-1.7.0 myproject pyramid-1.7.3 \
213     pyramid-debugtoolbar-3.0.5 pyramid-jinja2-2.7 pyramid-mako-1.0.2 \
214     repoze.lru-0.6 translationstring-1.3 venusian-1.0 waitress-1.0.1 \
215     zope.deprecation-4.2.0 zope.interface-4.3.3
54f2bb 216
a54e4c 217 This will install a :term:`distribution` representing your project into the
SP 218 virtual environment interpreter's library set so it can be found by ``import``
219 statements and by other console scripts such as ``pserve``, ``pshell``,
220 ``proutes``, and ``pviews``.
54f2bb 221
8c56ae 222 .. index::
c5f24b 223    single: running tests
CM 224    single: tests (running)
8c56ae 225
609a99 226 Running the Tests for Your Application
8e0dfc 227 --------------------------------------
54f2bb 228
f21b2b 229 To run unit tests for your application, you must first install the testing
SP 230 dependencies.
d0ec94 231
5af300 232 On Unix:
8f7262 233
d4177a 234 .. code-block:: bash
8f7262 235
f07408 236     $VENV/bin/pip install -e ".[testing]"
8e0dfc 237
f21b2b 238 On Windows:
8e0dfc 239
a651b3 240 .. code-block:: doscon
189c6e 241
f07408 242     %VENV%\Scripts\pip install -e ".[testing]"
f21b2b 243
SP 244 Once the testing requirements are installed, then you can run the tests using
f9c3ff 245 the ``pytest`` command that was just installed in the ``bin`` directory of
f21b2b 246 your virtual environment.
SP 247
5af300 248 On Unix:
f21b2b 249
SP 250 .. code-block:: bash
251
f9c3ff 252     $VENV/bin/pytest -q
f21b2b 253
SP 254 On Windows:
255
a651b3 256 .. code-block:: doscon
f21b2b 257
f9c3ff 258     %VENV%\Scripts\pytest -q
d0ec94 259
5af300 260 Here's sample output from a test run on Unix:
d0ec94 261
d4177a 262 .. code-block:: bash
d0ec94 263
f9c3ff 264     $VENV/bin/pytest -q
f07408 265     ..
SP 266     2 passed in 0.47 seconds
0bd226 267
28e688 268 The tests themselves are found in the ``tests.py`` module in your ``cookiecutter``-generated project.  Within a project generated by the ``pyramid-cookiecutter-starter`` cookiecutter, only two sample tests exist.
5ded35 269
SP 270 .. note::
271
f9c3ff 272     The ``-q`` option is passed to the ``pytest`` command to limit the output
f21b2b 273     to a stream of dots. If you don't pass ``-q``, you'll see verbose test
SP 274     result output (which normally isn't very useful).
e8561f 275
68ba58 276 Alternatively, if you'd like to see test coverage, pass the ``--cov`` option
f9c3ff 277 to ``pytest``:
68ba58 278
VF 279 .. code-block:: bash
280
f9c3ff 281     $VENV/bin/pytest --cov -q
e09369 282
f9c3ff 283 Cookiecutters include configuration defaults for ``pytest`` and test coverage.
e09369 284 These configuration files are ``pytest.ini`` and ``.coveragerc``, located at
SP 285 the root of your package. Without these defaults, we would need to specify the
286 path to the module on which we want to run tests and coverage.
287
288 .. code-block:: bash
289
f9c3ff 290     $VENV/bin/pytest --cov=myproject myproject/tests.py -q
e09369 291
9c39f6 292 .. seealso:: See ``pytest``'s documentation for :ref:`pytest:usage` or invoke
f9c3ff 293    ``pytest -h`` to see its full set of options.
68ba58 294
VF 295
9ec2d6 296 .. index::
CM 297    single: running an application
cfb2b5 298    single: pserve
9ec2d6 299    single: reload
CM 300    single: startup
301
eb3b27 302 .. _running_the_project_application:
KOP 303
609a99 304 Running the Project Application
e0fc0b 305 -------------------------------
0bc787 306
fa257d 307 .. seealso:: See also the output of :ref:`pserve --help <pserve_script>`.
5ff3d2 308
a119be 309 Once a project is installed for development, you can run the application it
cfb2b5 310 represents using the ``pserve`` command against the generated configuration
CM 311 file.  In our case, this file is named ``development.ini``.
d0ec94 312
5af300 313 On Unix:
0bc787 314
d4177a 315 .. code-block:: bash
793425 316
f07408 317     $VENV/bin/pserve development.ini
793425 318
d0ec94 319 On Windows:
CM 320
e1b26e 321 .. code-block:: doscon
d0ec94 322
f07408 323     %VENV%\Scripts\pserve development.ini
d0ec94 324
5af300 325 Here's sample output from a run of ``pserve`` on Unix:
189c6e 326
d4177a 327 .. code-block:: bash
189c6e 328
f07408 329     $VENV/bin/pserve development.ini
SP 330     Starting server in PID 77171.
331     Serving on http://localhost:6543
332     Serving on http://localhost:6543
0bc787 333
d4177a 334 Access is restricted such that only a browser running on the same machine as
SP 335 Pyramid will be able to access your Pyramid application.  However, if you want
336 to open access to other machines on the same network, then edit the
07e802 337 ``development.ini`` file, and replace the ``listen`` value in the
b57460 338 ``[server:main]`` section, changing it from ``localhost:6543`` to ``*:6543``
fb17a3 339 (this is equivalent to ``0.0.0.0:6543 [::]:6543``).  For example:
38669d 340
TL 341 .. code-block:: ini
dace59 342
f07408 343     [server:main]
SP 344     use = egg:waitress#main
345     listen = *:6543
d4177a 346
SP 347 Now when you use ``pserve`` to start the application, it will respond to
348 requests on *all* IP addresses possessed by your system, not just requests to
349 ``localhost``.  This is what the ``0.0.0.0`` in
350 ``serving on http://0.0.0.0:6543`` means.  The server will respond to requests
351 made to ``127.0.0.1`` and on any external IP address. For example, your system
352 might be configured to have an external IP address ``192.168.1.50``.  If that's
353 the case, if you use a browser running on the same system as Pyramid, it will
354 be able to access the application via ``http://127.0.0.1:6543/`` as well as via
355 ``http://192.168.1.50:6543/``. However, *other people* on other computers on
356 the same network will also be able to visit your Pyramid application in their
3c5731 357 browser by visiting ``http://192.168.1.50:6543/``. The same holds true if you use
M 358 IPv6. ``[::]`` means the same as ``0.0.0.0`` but for IPv6 protocol.
dace59 359
CM 360 You can change the port on which the server runs on by changing the same
361 portion of the ``development.ini`` file.  For example, you can change the
b57460 362 ``listen = localhost:6543`` line in the ``development.ini`` file's ``[server:main]``
SP 363 section to ``listen = localhost:8080`` to run the server on port 8080 instead of port 6543.
dace59 364
609a99 365 You can shut down a server started this way by pressing ``Ctrl-C`` (or
SP 366 ``Ctrl-Break`` on Windows).
a119be 367
7a89a4 368 The default server used to run your Pyramid application when a project is
e1b26e 369 created from a cookiecutter is named :term:`Waitress`.  This server is what prints
SP 370 the ``Serving on...`` line when you run ``pserve``.  It's a good idea to use
a54e4c 371 this server during development because it's very simple.  It can also be used
SP 372 for light production.  Setting your application up under a different server is
373 not advised until you've done some development work under the default server,
374 particularly if you're not yet experienced with Python web development.  Python
375 web server setup can be complex, and you should get some confidence that your
376 application works in a default environment before trying to optimize it or make
377 it "more like production".  It's awfully easy to get sidetracked trying to set
378 up a non-default server for hours without actually starting to do any
379 development.  One of the nice things about Python web servers is that they're
380 largely interchangeable, so if your application works under the default server,
381 it will almost certainly work under any other server in production if you
382 eventually choose to use a different one.  Don't worry about it right now.
7a89a4 383
CM 384 For more detailed information about the startup process, see
385 :ref:`startup_chapter`.  For more information about environment variables and
386 configuration file settings that influence startup and runtime behavior, see
387 :ref:`environment_chapter`.
388
389 .. _reloading_code:
390
391 Reloading Code
392 ~~~~~~~~~~~~~~
393
a54e4c 394 During development, it's often useful to run ``pserve`` using its ``--reload``
SP 395 option.  When ``--reload`` is passed to ``pserve``, changes to any Python
396 module your project uses will cause the server to restart.  This typically
397 makes development easier, as changes to Python code made within a
cfb2b5 398 :app:`Pyramid` application is not put into effect until the server restarts.
9ec2d6 399
5af300 400 For example, on Unix:
9ec2d6 401
CM 402 .. code-block:: text
403
f07408 404     $VENV/bin/pserve development.ini --reload
SP 405     Starting subprocess with file monitor
406     Starting server in PID 16601.
407     Serving on http://localhost:6543
408     Serving on http://localhost:6543
6ce1e0 409
5991d9 410 Now if you make a change to any of your project's ``.py`` files or ``.ini``
CM 411 files, you'll see the server restart automatically:
412
413 .. code-block:: text
414
f07408 415     development.ini changed; reloading...
SP 416     -------------------- Restarting --------------------
417     Starting server in PID 16602.
418     Serving on http://localhost:6543
419     Serving on http://localhost:6543
5991d9 420
CM 421 Changes to template files (such as ``.pt`` or ``.mak`` files) won't cause the
a54e4c 422 server to restart.  Changes to template files don't require a server restart as
SP 423 long as the ``pyramid.reload_templates`` setting in the ``development.ini``
e1b26e 424 file is ``true``.  Changes made to template files when this setting is ``true``
a54e4c 425 will take effect immediately without a server restart.
5991d9 426
6ce1e0 427 .. index::
CM 428    single: WSGI
b17af4 429
0bc787 430 Viewing the Application
CM 431 -----------------------
432
cfb2b5 433 Once your application is running via ``pserve``, you may visit
a119be 434 ``http://localhost:6543/`` in your browser.  You will see something in your
CM 435 browser like what is displayed in the following image:
0bc787 436
eff462 437 .. image:: project.png
0bc787 438
e1b26e 439 This is the page shown by default when you visit an unmodified ``cookiecutter``
28e688 440 generated ``pyramid-cookiecutter-starter`` application in a browser.
a119be 441
2c9f3c 442 .. index::
CM 443    single: debug toolbar
444
445 .. _debug_toolbar:
446
447 The Debug Toolbar
448 ~~~~~~~~~~~~~~~~~
449
609a99 450 .. image:: project-show-toolbar.png
SP 451
452 If you click on the :app:`Pyramid` logo at the top right of the page, a new
453 target window will open to present a debug toolbar that provides various
a54e4c 454 niceties while you're developing.  This logo will float above every HTML page
SP 455 served by :app:`Pyramid` while you develop an application, and allows you to
456 show the toolbar as necessary.
c6d9f1 457
CM 458 .. image:: project-debug.png
459
a54e4c 460 If you don't see the Pyramid logo on the top right of the page, it means you're
SP 461 browsing from a system that does not have debugging access.  By default, for
462 security reasons, only a browser originating from ``localhost`` (``127.0.0.1``)
463 can see the debug toolbar.  To allow your browser on a remote system to access
464 the server, add a line within the ``[app:main]`` section of the
465 ``development.ini`` file in the form ``debugtoolbar.hosts = X .X.X.X``.  For
466 example, if your Pyramid application is running on a remote system, and you're
467 browsing from a host with the IP address ``192.168.1.1``, you'd add something
468 like this to enable the toolbar when your system contacts Pyramid:
9bdb09 469
CM 470 .. code-block:: ini
471
f07408 472     [app:main]
SP 473     # .. other settings ...
474     debugtoolbar.hosts = 192.168.1.1
9bdb09 475
f21b2b 476 For more information about what the debug toolbar allows you to do, see the
SP 477 :ref:`documentation for pyramid_debugtoolbar <toolbar:overview>`.
c6d9f1 478
a54e4c 479 The debug toolbar will not be shown (and all debugging will be turned off) when
SP 480 you use the ``production.ini`` file instead of the ``development.ini`` ini file
481 to run the application.
c6d9f1 482
06247f 483 You can also turn the debug toolbar off by editing ``development.ini`` and
d21ba4 484 commenting out a line.  For example, instead of:
06247f 485
CM 486 .. code-block:: ini
f07408 487     :linenos:
06247f 488
f07408 489     [app:main]
SP 490     # ... elided configuration
491     pyramid.includes =
492         pyramid_debugtoolbar
06247f 493
d21ba4 494 Put a hash mark at the beginning of the ``pyramid_debugtoolbar`` line:
06247f 495
CM 496 .. code-block:: ini
f07408 497     :linenos:
06247f 498
f07408 499     [app:main]
SP 500     # ... elided configuration
501     pyramid.includes =
502     #    pyramid_debugtoolbar
06247f 503
CM 504 Then restart the application to see that the toolbar has been turned off.
8f7262 505
f57b56 506 Note that if you comment out the ``pyramid_debugtoolbar`` line, the ``#``
a54e4c 507 *must* be in the first column.  If you put it anywhere else, and then attempt
SP 508 to restart the application, you'll receive an error that ends something like
509 this:
d21ba4 510
CM 511 .. code-block:: text
512
f07408 513     ImportError: No module named #pyramid_debugtoolbar
d21ba4 514
8c56ae 515 .. index::
CM 516    single: project structure
517
0bc787 518 The Project Structure
CM 519 ---------------------
520
28e688 521 The ``pyramid-cookiecutter-starter`` cookiecutter generated a :term:`project` (named ``myproject``),
cfb2b5 522 which contains a Python :term:`package`.  The package is *also* named
e1b26e 523 ``myproject``; the cookiecutter generates a project which
SP 524 contains a package that shares its name.
0bc787 525
e1b26e 526 All :app:`Pyramid` ``cookiecutter``-generated projects share a similar structure.
SP 527 The ``myproject`` project we've generated has the following directory structure:
5d22ee 528
BL 529 .. code-block:: text
0bc787 530
7f5a79 531     myproject
f07408 532     â”œâ”€â”€ .coveragerc
7f5a79 533     â”œâ”€â”€ .gitignore
f07408 534     â”œâ”€â”€ CHANGES.txt
SP 535     â”œâ”€â”€ MANIFEST.in
536     â”œâ”€â”€ myproject
537     â”‚   â”œâ”€â”€ __init__.py
7f5a79 538     â”‚   â”œâ”€â”€ routes.py
f07408 539     â”‚   â”œâ”€â”€ static
SP 540     â”‚   â”‚   â”œâ”€â”€ pyramid-16x16.png
541     â”‚   â”‚   â”œâ”€â”€ pyramid.png
542     â”‚   â”‚   â””── theme.css
543     â”‚   â”œâ”€â”€ templates
7f5a79 544     â”‚   â”‚   â”œâ”€â”€ 404.jinja2
f07408 545     â”‚   â”‚   â”œâ”€â”€ layout.jinja2
SP 546     â”‚   â”‚   â””── mytemplate.jinja2
547     â”‚   â”œâ”€â”€ tests.py
7f5a79 548     â”‚   â””── views
SP 549     â”‚       â”œâ”€â”€ __init__.py
550     â”‚       â”œâ”€â”€ default.py
551     â”‚       â””── notfound.py
f07408 552     â”œâ”€â”€ README.txt
SP 553     â”œâ”€â”€ development.ini
554     â”œâ”€â”€ production.ini
555     â”œâ”€â”€ pytest.ini
556     â””── setup.py
0bc787 557
e1b26e 558
SP 559 The ``myproject`` :term:`Project`
178623 560 ---------------------------------
0bc787 561
e1b26e 562 The ``myproject`` :term:`project` directory is the distribution and deployment
a54e4c 563 wrapper for your application.  It contains both the ``myproject``
178623 564 :term:`package` representing your application as well as files used to
CM 565 describe, run, and test your application.
0bc787 566
e1b26e 567 #. ``.coveragerc`` configures coverage when running tests.
7f5a79 568
SP 569 #. ``.gitignore`` tells git which files and directories to ignore from source code version control.
e1b26e 570
a54e4c 571 #. ``CHANGES.txt`` describes the changes you've made to the application.  It is
e1b26e 572    conventionally written in :term:`reStructuredText` format.
SP 573
574 #. ``MANIFEST.in`` is a :term:`distutils` "manifest" file, naming which files
575    should be included in a source distribution of the package when ``python
576    setup.py sdist`` is run.
0bc787 577
a119be 578 #. ``README.txt`` describes the application in general.  It is conventionally
e1b26e 579    written in :term:`reStructuredText` format.
0bc787 580
a54e4c 581 #. ``development.ini`` is a :term:`PasteDeploy` configuration file that can be
SP 582    used to execute your application during development.
43ab04 583
a54e4c 584 #. ``production.ini`` is a :term:`PasteDeploy` configuration file that can be
SP 585    used to execute your application in a production configuration.
47442f 586
e1b26e 587 #. ``pytest.ini`` is a configuration file for running tests.
1f884e 588
a54e4c 589 #. ``setup.py`` is the file you'll use to test and distribute your application.
315e46 590    It is a standard :term:`Setuptools` ``setup.py`` file.
1f884e 591
8c56ae 592 .. index::
CM 593    single: PasteDeploy
594    single: ini file
543024 595
e1b26e 596 .. _myproject_ini:
c6e58b 597
9f0269 598 ``development.ini``
CM 599 ~~~~~~~~~~~~~~~~~~~
543024 600
a54e4c 601 The ``development.ini`` file is a :term:`PasteDeploy` configuration file. Its
SP 602 purpose is to specify an application to run when you invoke ``pserve``, as well
603 as the deployment settings provided to that application.
543024 604
9f0269 605 The generated ``development.ini`` file looks like so:
543024 606
e1b26e 607 .. literalinclude:: myproject/development.ini
edf394 608    :language: ini
543024 609    :linenos:
CM 610
9573ac 611 This file contains several sections including ``[app:main]``,
a54e4c 612 ``[server:main]``, and several other sections related to logging configuration.
543024 613
3d338e 614 The ``[app:main]`` section represents configuration for your :app:`Pyramid`
a54e4c 615 application.  The ``use`` setting is the only setting required to be present in
e1b26e 616 the ``[app:main]`` section.  Its default value, ``egg:myproject``, indicates
SP 617 that our myproject project contains the application that should be served. 
a54e4c 618 Other settings added to this section are passed as keyword arguments to the
SP 619 function named ``main`` in our package's ``__init__.py`` module.  You can
620 provide startup-time configuration parameters to your application by adding
621 more settings to this section.
e35dc1 622
058e90 623 .. seealso:: See :ref:`pastedeploy_entry_points` for more information about the
e1b26e 624    meaning of the ``use = egg:myproject`` value in this section.
3d338e 625
CM 626 The ``pyramid.reload_templates`` setting in the ``[app:main]`` section is a
058e90 627 :app:`Pyramid`-specific setting which is passed into the framework.  If it
a54e4c 628 exists, and its value is ``true``, supported template changes will not require
SP 629 an application restart to be detected.  See :ref:`reload_templates_section` for
630 more information.
e35dc1 631
488ea0 632 .. warning:: The ``pyramid.reload_templates`` option should be turned off for
CM 633    production applications, as template rendering is slowed when it is turned
634    on.
7c525f 635
a54e4c 636 The ``pyramid.includes`` setting in the ``[app:main]`` section tells Pyramid to
SP 637 "include" configuration from another package.  In this case, the line
3d338e 638 ``pyramid.includes = pyramid_debugtoolbar`` tells Pyramid to include
c6d9f1 639 configuration from the ``pyramid_debugtoolbar`` package.  This turns on a
058e90 640 debugging panel in development mode which can be opened by clicking on the
SP 641 :app:`Pyramid` logo on the top right of the screen.  Including the debug
642 toolbar will also make it possible to interactively debug exceptions when an
643 error occurs.
c6d9f1 644
a54e4c 645 Various other settings may exist in this section having to do with debugging or
SP 646 influencing runtime behavior of a :app:`Pyramid` application.  See
a3ceb6 647 :ref:`environment_chapter` for more information about these settings.
CM 648
3d338e 649 The name ``main`` in ``[app:main]`` signifies that this is the default
cfb2b5 650 application run by ``pserve`` when it is invoked against this configuration
a54e4c 651 file.  The name ``main`` is a convention used by PasteDeploy signifying that it
SP 652 is the default application.
b65d8e 653
a119be 654 The ``[server:main]`` section of the configuration file configures a WSGI
d4177a 655 server which listens on TCP port 6543.  It is configured to listen on localhost
SP 656 only (``127.0.0.1``).
543024 657
e1b26e 658 .. _myproject_ini_logging:
eb3b27 659
d4177a 660 The sections after ``# logging configuration`` represent Python's standard
SP 661 library :mod:`logging` module configuration for your application.  These
662 sections are passed to the `logging module's config file configuration engine
1cb30e 663 <https://docs.python.org/2/howto/logging.html#configuring-logging>`_ when the
d4177a 664 ``pserve`` or ``pshell`` commands are executed.  The default configuration
a54e4c 665 sends application logging output to the standard error output of your terminal.
SP 666 For more information about logging configuration, see :ref:`logging_chapter`.
f4a804 667
a119be 668 See the :term:`PasteDeploy` documentation for more information about other
CM 669 types of things you can put into this ``.ini`` file, such as other
058e90 670 applications, :term:`middleware`, and alternate :term:`WSGI` server
a119be 671 implementations.
543024 672
6ce1e0 673 .. index::
CM 674    single: production.ini
675
43ab04 676 ``production.ini``
609a99 677 ~~~~~~~~~~~~~~~~~~
43ab04 678
a54e4c 679 The ``production.ini`` file is a :term:`PasteDeploy` configuration file with a
SP 680 purpose much like that of ``development.ini``.  However, it disables the debug
681 toolbar, and filters all log messages except those above the WARN level.  It
682 also turns off template development options such that templates are not
683 automatically reloaded when changed, and turns off all debugging options.  This
684 file is appropriate to use instead of ``development.ini`` when you put your
685 application into production.
f601bd 686
2b65bb 687 It's important to use ``production.ini`` (and *not* ``development.ini``) to
CM 688 benchmark your application and put it into production.  ``development.ini``
689 configures your system with a debug toolbar that helps development, but the
690 inclusion of this toolbar slows down page rendering times by over an order of
a54e4c 691 magnitude.  The debug toolbar is also a potential security risk if you have it
SP 692 configured incorrectly.
2b65bb 693
f601bd 694 .. index::
CM 695    single: MANIFEST.in
696
697 ``MANIFEST.in``
698 ~~~~~~~~~~~~~~~
699
700 The ``MANIFEST.in`` file is a :term:`distutils` configuration file which
701 specifies the non-Python files that should be included when a
702 :term:`distribution` of your Pyramid project is created when you run ``python
703 setup.py sdist``.  Due to the information contained in the default
a54e4c 704 ``MANIFEST.in``, an sdist of your Pyramid project will include ``.txt`` files,
SP 705 ``.ini`` files, ``.rst`` files, graphics files, and template files, as well as
706 ``.py`` files.  See
1cb30e 707 https://docs.python.org/2/distutils/sourcedist.html#the-manifest-in-template
SP 708 for more information about the syntax and usage of ``MANIFEST.in``.
43ab04 709
a54e4c 710 Without the presence of a ``MANIFEST.in`` file or without checking your source
SP 711 code into a version control repository, ``setup.py sdist`` places only *Python
712 source files* (files ending with a ``.py`` extension) into tarballs generated
713 by ``python setup.py sdist``.  This means, for example, if your project was not
315e46 714 checked into a Setuptools-compatible source control system, and your project
a54e4c 715 directory didn't contain a ``MANIFEST.in`` file that told the ``sdist``
SP 716 machinery to include ``*.pt`` files, the ``myproject/templates/mytemplate.pt``
717 file would not be included in the generated tarball.
01815e 718
e1b26e 719 Projects generated by Pyramid cookiecutters include a default ``MANIFEST.in`` file.
a54e4c 720 The ``MANIFEST.in`` file contains declarations which tell it to include files
SP 721 like ``*.pt``, ``*.css`` and ``*.js`` in the generated tarball. If you include
722 files with extensions other than the files named in the project's
315e46 723 ``MANIFEST.in`` and you don't make use of a Setuptools-compatible version
a54e4c 724 control system, you'll need to edit the ``MANIFEST.in`` file and include the
SP 725 statements necessary to include your new files.  See
1cb30e 726 https://docs.python.org/2/distutils/sourcedist.html#principle for more
SP 727 information about how to do this.
01815e 728
315e46 729 You can also delete ``MANIFEST.in`` from your project and rely on a :term:`Setuptools`
a54e4c 730 feature which simply causes all files checked into a version control system to
SP 731 be put into the generated tarball.  To allow this to happen, check all the
732 files that you'd like to be distributed along with your application's Python
733 files into Subversion.  After you do this, when you rerun ``setup.py sdist``,
734 all files checked into the version control system will be included in the
735 tarball.  If you don't use Subversion, and instead use a different version
315e46 736 control system, you may need to install a :term:`Setuptools` add-on such as
a54e4c 737 ``setuptools-git`` or ``setuptools-hg`` for this behavior to work properly.
01815e 738
8c56ae 739 .. index::
CM 740    single: setup.py
741
543024 742 ``setup.py``
CM 743 ~~~~~~~~~~~~
744
315e46 745 The ``setup.py`` file is a :term:`Setuptools` setup file.  It is meant to be
f21b2b 746 used to define requirements for installing dependencies for your package and
SP 747 testing, as well as distributing your application.
5ded35 748
SP 749 .. note::
750
a54e4c 751    ``setup.py`` is the de facto standard which Python developers use to
SP 752    distribute their reusable code.  You can read more about ``setup.py`` files
f21b2b 753    and their usage in the `Python Packaging User Guide
a816a8 754    <https://packaging.python.org/>`_ and `Setuptools documentation
9ce94f 755    <https://setuptools.readthedocs.io/en/latest/>`_.
543024 756
CM 757 Our generated ``setup.py`` looks like this:
758
e1b26e 759 .. literalinclude:: myproject/setup.py
5d22ee 760    :language: python
543024 761    :linenos:
CM 762
315e46 763 The ``setup.py`` file calls the :term:`Setuptools` ``setup`` function, which does
f21b2b 764 various things depending on the arguments passed to ``pip`` on the command
a54e4c 765 line.
543024 766
a54e4c 767 Within the arguments to this function call, information about your application
SP 768 is kept.  While it's beyond the scope of this documentation to explain
315e46 769 everything about :term:`Setuptools` setup files, we'll provide a whirlwind tour of what
a54e4c 770 exists in this file in this section.
543024 771
a3ceb6 772 Your application's name can be any string; it is specified in the ``name``
CM 773 field.  The version number is specified in the ``version`` value.  A short
a54e4c 774 description is provided in the ``description`` field.  The ``long_description``
f21b2b 775 is conventionally the content of the ``README`` and ``CHANGES`` files appended
1cb30e 776 together. The ``classifiers`` field is a list of `Trove classifiers
8bd6f7 777 <https://pypi.org/pypi?%3Aaction=list_classifiers>`_ describing your
1cb30e 778 application.  ``author`` and ``author_email`` are text fields which probably
SP 779 don't need any description. ``url`` is a field that should point at your
780 application project's URL (if any). ``packages=find_packages()`` causes all
781 packages within the project to be found when packaging the application.
782 ``include_package_data`` will include non-Python files when the application is
783 packaged if those files are checked into version control. ``zip_safe=False``
784 indicates that this package is not safe to use as a zipped egg; instead it will
785 always unpack as a directory, which is more convenient. ``install_requires``
786 indicates that this package depends on the ``pyramid`` package.
787 ``extras_require`` is a Python dictionary that defines what is required to be
788 installed for running tests. We examined ``entry_points`` in our discussion of
789 the ``development.ini`` file; this file defines the ``main`` entry point that
790 represents our project's application.
543024 791
a54e4c 792 Usually you only need to think about the contents of the ``setup.py`` file when
SP 793 distributing your application to other people, when adding Python package
794 dependencies, or when versioning your application for your own use. For fun,
795 you can try this command now:
543024 796
5d22ee 797 .. code-block:: text
9ec2d6 798
f07408 799     $VENV/bin/python setup.py sdist
543024 800
a54e4c 801 This will create a tarball of your application in a ``dist`` subdirectory named
e1b26e 802 ``myproject-0.0.tar.gz``.  You can send this tarball to other people who want
a54e4c 803 to install and use your application.
7534ba 804
8c56ae 805 .. index::
CM 806    single: package
807
178623 808 The ``myproject`` :term:`Package`
CM 809 ---------------------------------
1f884e 810
e1b26e 811 The ``myproject`` :term:`package` lives inside the ``myproject``
178623 812 :term:`project`.  It contains:
1f884e 813
a54e4c 814 #. An ``__init__.py`` file signifies that this is a Python :term:`package`. It
SP 815    also contains code that helps users run the application, including a
f8869c 816    ``main`` function which is used as a entry point for commands such as
CM 817    ``pserve``, ``pshell``, ``pviews``, and others.
1f884e 818
e1b26e 819 #. A ``templates`` directory, which contains :term:`Jinja2` (or other types
a54e4c 820    of) templates.
1f884e 821
a54e4c 822 #. A ``tests.py`` module, which contains unit test code for the application.
1f884e 823
6b6d0e 824 #. A ``routes.py`` module, which contains routing code for the application.
SM 825
7f5a79 826 #. A ``views`` package, which contains view code for the application.
SP 827
828 #. A ``static`` directory, which contains static files, including images and CSS.
1f884e 829
e1b26e 830 These are purely conventions established by the cookiecutter. :app:`Pyramid`
058e90 831 doesn't insist that you name things in any particular way. However, it's
SP 832 generally a good idea to follow Pyramid standards for naming, so that other
833 Pyramid developers can get up to speed quickly on your code when you need help.
8c56ae 834
CM 835 .. index::
9f0269 836    single: __init__.py
1f884e 837
f601bd 838 .. _init_py:
CM 839
9f0269 840 ``__init__.py``
CM 841 ~~~~~~~~~~~~~~~
1f884e 842
9f0269 843 We need a small Python module that configures our application and which
CM 844 advertises an entry point for use by our :term:`PasteDeploy` ``.ini`` file.
845 This is the file named ``__init__.py``.  The presence of an ``__init__.py``
846 also informs Python that the directory which contains it is a *package*.
1f884e 847
e1b26e 848 .. literalinclude:: myproject/myproject/__init__.py
5d22ee 849    :language: python
1f884e 850    :linenos:
CM 851
a119be 852 #. Line 1 imports the :term:`Configurator` class from :mod:`pyramid.config`
CM 853    that we use later.
1f884e 854
2207ed 855 #. Lines 4-12 define a function named ``main`` that returns a :app:`Pyramid`
f601bd 856    WSGI application.  This function is meant to be called by the
cfb2b5 857    :term:`PasteDeploy` framework as a result of running ``pserve``.
9f0269 858
429029 859    Within this function, application configuration is performed.
9f0269 860
6b6d0e 861    Line 7 opens a context manager with an instance of a :term:`Configurator`.
9bbaa8 862
e1b26e 863    Line 8 adds support for Jinja2 templating bindings, allowing us to
SP 864    specify renderers with the ``.jinja2`` extension.
2207ed 865
7f5a79 866    Line 9 includes the ``routes.py`` module.
eff462 867
7f5a79 868    Line 10 calls ``config.scan()``, which picks up view registrations declared
8fe021 869    elsewhere in the package (in this case, in the ``views.py`` module).
8595a7 870
7f5a79 871    Line 11 returns a :term:`WSGI` application to the caller of the function
f8869c 872    (Pyramid's pserve).
7f5a79 873
SP 874
875 .. index::
876     single: routes.py
877
878 .. _routes_py:
879
880 ``routes.py``
881 ~~~~~~~~~~~~~
882
883 The ``routes.py`` module gets included by the ``main`` function in our ``__init__.py``.
884 It registers a view and a route.
885
886 .. literalinclude:: myproject/myproject/routes.py
887     :language: python
888     :linenos:
889
890 Line 2 registers a static view, which will serve up the files from the ``myproject:static`` :term:`asset specification` (the ``static`` directory of the ``myproject`` package).
891
892 Line 3 adds a :term:`route` to the configuration.  This route is later used by a view in the ``views`` module.
893
8c56ae 894
6ce1e0 895 .. index::
CM 896    single: views.py
897
7f5a79 898 ``views`` package
SP 899 ~~~~~~~~~~~~~~~~~
0bc787 900
a119be 901 Much of the heavy lifting in a :app:`Pyramid` application is done by *view
CM 902 callables*.  A :term:`view callable` is the main tool of a :app:`Pyramid` web
a54e4c 903 application developer; it is a bit of code which accepts a :term:`request` and
SP 904 which returns a :term:`response`.
0bc787 905
7f5a79 906 Our project has a ``views`` package by virtue of it being a directory containing an ``__init__.py`` file.
SP 907 This ``__init__.py`` file happens to have no content, although it could as a project develops.
908
909 We have two view modules in the ``views`` package.
910 Let's look at ``default.py``.
911
912 .. literalinclude:: myproject/myproject/views/default.py
5d22ee 913    :language: python
1f884e 914    :linenos:
0bc787 915
d85569 916 Lines 4-6 define and register a :term:`view callable` named ``my_view``.  The
a54e4c 917 function named ``my_view`` is decorated with a ``view_config`` decorator (which
SP 918 is processed by the ``config.scan()`` line in our ``__init__.py``). The
919 view_config decorator asserts that this view be found when a :term:`route`
7f5a79 920 named ``home`` is matched.  In our case, because our ``routes.py`` maps the
a54e4c 921 route named ``home`` to the URL pattern ``/``, this route will match when a
SP 922 visitor visits the root URL.  The view_config decorator also names a
923 ``renderer``, which in this case is a template that will be used to render the
924 result of the view callable.  This particular view declaration points at
7f5a79 925 ``../templates/mytemplate.jinja2``, which is an :term:`asset specification` that
SP 926 specifies the ``mytemplate.jinja2`` file within the ``templates`` directory of the
a54e4c 927 ``myproject`` package.  The asset specification could have also been specified
7f5a79 928 as ``myproject:templates/mytemplate.jinja2``; the leading package name and colon is
e1b26e 929 optional.  The template file pointed to is a :term:`Jinja2` template
7f5a79 930 file (``templates/mytemplate.jinja2``).
1f884e 931
a119be 932 This view callable function is handed a single piece of information: the
a54e4c 933 :term:`request`.  The *request* is an instance of the :term:`WebOb` ``Request``
SP 934 class representing the browser's request to our server.
1f884e 935
47e13e 936 This view is configured to invoke a :term:`renderer` on a template.  The
f24ac4 937 dictionary the view returns (on line 6) provides the value the renderer
a54e4c 938 substitutes into the template when generating HTML.  The renderer then returns
SP 939 the HTML in a :term:`response`.
9bbaa8 940
5276ce 941 .. note:: Dictionaries provide values to :term:`template`\s.
7f5a79 942
SP 943 Now let's look at ``notfound.py``.
944
945 .. literalinclude:: myproject/myproject/views/notfound.py
946    :language: python
947    :linenos:
948
949 This file is similar to ``default.py``.
950 It merely returns a ``404`` response status and an empty dictionary to the template at ``../templates/404.jinja2``.
5276ce 951
e1b26e 952 .. note:: When the application is run with the cookiecutter's :ref:`default
SP 953    development.ini <myproject_ini>` configuration, :ref:`logging is set up
954    <myproject_ini_logging>` to aid debugging.  If an exception is raised,
6b2e8e 955    uncaught tracebacks are displayed after the startup messages on :ref:`the
SP 956    console running the server <running_the_project_application>`. Also
a54e4c 957    ``print()`` statements may be inserted into the application for debugging to
SP 958    send output to this console.
eb3b27 959
56170f 960 .. note:: ``development.ini`` has a setting that controls how templates are
5ded35 961    reloaded, ``pyramid.reload_templates``.
56170f 962
e1b26e 963    - When set to ``True`` (as in the cookiecutter ``development.ini``), changed
5ded35 964      templates automatically reload without a server restart.  This is
SP 965      convenient while developing, but slows template rendering speed.
966
a54e4c 967    - When set to ``False`` (the default value), changing templates requires a
SP 968      server restart to reload them.  Production applications should use
56170f 969      ``pyramid.reload_templates = False``.
8c56ae 970
2033ee 971 .. seealso::
SP 972
a54e4c 973     See also :ref:`views_which_use_a_renderer` for more information about how
SP 974     views, renderers, and templates relate and cooperate.
5ded35 975
2033ee 976 .. seealso::
5ded35 977
2033ee 978     Pyramid can also dynamically reload changed Python files.  See also
SP 979     :ref:`reloading_code`.
980
981 .. seealso::
982
983     See also the :ref:`debug_toolbar`, which provides interactive access to
984     your application's internals and, should an exception occur, allows
985     interactive access to traceback execution stack frames from the Python
986     interpreter.
5ded35 987
6ce1e0 988 .. index::
CM 989    single: static directory
990
fb3003 991 ``static``
a5ffd6 992 ~~~~~~~~~~
fb3003 993
e1b26e 994 This directory contains static assets which support the ``layout.jinja2``
a5ffd6 995 template.  It includes CSS and images.
fb3003 996
e1b26e 997
SP 998 ``templates/layout.jinja2``
1f884e 999 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
CM 1000
e1b26e 1001 This is the base layout content. It contains a single marker for content block. Other templates inherit its content, providing layout for the web application. Its contents are too long to show here, but here is an excerpt:
SP 1002
1003 .. literalinclude:: myproject/myproject/templates/layout.jinja2
1004    :language: jinja
1005    :lines: 34-38
1006    :lineno-match:
1007
1008
1009 ``templates/mytemplate.jinja2``
1010 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1011
1012 This is the content :term:`Jinja2` template that exists in the project.  It is referenced by the call to ``@view_config`` as the ``renderer``
7f5a79 1013 of the ``my_view`` view callable in the ``views/default.py`` file.  See
e1b26e 1014 :ref:`views_which_use_a_renderer` for more information about renderers. It inherits ("extends") the HTML provided by ``layout.jinja2``, replacing the content block with its own content.
SP 1015
1016 .. literalinclude:: myproject/myproject/templates/mytemplate.jinja2
1017    :language: jinja
1018    :linenos:
eff462 1019
a119be 1020 Templates are accessed and used by view configurations and sometimes by view
CM 1021 functions themselves.  See :ref:`templates_used_directly` and
9ec2d6 1022 :ref:`templates_used_as_renderers`.
7f5a79 1023
SP 1024
1025 ``templates/404.jinja2``
1026 ~~~~~~~~~~~~~~~~~~~~~~~~
1027
1028 This template is similar to ``mytemplate.jinja2``, but with a few differences.
1029 It is referenced by the call to ``@notfound_view_config`` as the ``renderer`` of the ``notfound_view`` view callable in the ``views/notfound.py`` file.
1030 It inherits the HTML provided by ``layout.jinja2``, replacing the content block with its own content.
1031
1032 .. literalinclude:: myproject/myproject/templates/404.jinja2
1033    :language: jinja
1034    :linenos:
e1b26e 1035
8c56ae 1036
f52d59 1037 .. index::
CM 1038    single: tests.py
1039
1f884e 1040 ``tests.py``
CM 1041 ~~~~~~~~~~~~
1042
e1b26e 1043 The ``tests.py`` module includes tests for your application.
1f884e 1044
e1b26e 1045 .. literalinclude:: myproject/myproject/tests.py
5d22ee 1046    :language: python
1f884e 1047    :linenos:
CM 1048
f21b2b 1049 This sample ``tests.py`` file has one unit test and one functional test defined
f9c3ff 1050 within it. These tests are executed when you run ``pytest -q``. You may add
ea252c 1051 more tests here as you build your application. You are not required to write
SP 1052 tests to use :app:`Pyramid`. This file is simply provided for convenience and
1053 example.
0bc787 1054
6ee49a 1055 See :ref:`testing_chapter` for more information about writing :app:`Pyramid`
CM 1056 unit tests.
aa3306 1057
6ce1e0 1058 .. index::
CM 1059    pair: modifying; package structure
1060
fd9c5b 1061 .. _modifying_package_structure:
CM 1062
aa3306 1063 Modifying Package Structure
609a99 1064 ---------------------------
aa3306 1065
CM 1066 It is best practice for your application's code layout to not stray too much
e1b26e 1067 from accepted Pyramid cookiecutter defaults.  If you refrain from changing things
a54e4c 1068 very much, other Pyramid coders will be able to more quickly understand your
e1b26e 1069 application.  However, the code layout choices made for you by a cookiecutter are
a54e4c 1070 in no way magical or required.  Despite the choices made for you by any
e1b26e 1071 cookiecutter, you can decide to lay your code out any way you see fit.
aa3306 1072
CM 1073 For example, the configuration method named
d7f259 1074 :meth:`~pyramid.config.Configurator.add_view` requires you to pass a
aa3306 1075 :term:`dotted Python name` or a direct object reference as the class or
7f5a79 1076 function to be used as a view.
SP 1077 By default, the ``starter`` cookiecutter would have you create a ``views`` directory, and add a single file for each view or collection of related views.
1078 However, you might be more comfortable creating a single ``views.py`` module in your package and add view functions to it.
aa3306 1079
7f5a79 1080 Whatever structure you prefer, as long as you use the ``@view_config`` directive
a54e4c 1081 to register views in conjunction with ``config.scan()``, they will be picked up
SP 1082 automatically when the application is restarted.
aa3306 1083
ae4c57 1084 Using the Interactive Shell
CM 1085 ---------------------------
1086
926fbe 1087 It is possible to use the ``pshell`` command to load a Python interpreter
a54e4c 1088 prompt with a similar configuration as would be loaded if you were running your
SP 1089 Pyramid application via ``pserve``.  This can be a useful debugging tool. See
1090 :ref:`interactive_shell` for more details.
ae4c57 1091
47eaa1 1092 .. _what_is_this_pserve_thing:
PE 1093
c3a36b 1094 What Is This ``pserve`` Thing
CM 1095 -----------------------------
d83b39 1096
e1b26e 1097 The code generated by a :app:`Pyramid` cookiecutter assumes that you will be using
058e90 1098 the ``pserve`` command to start your application while you do development.
SP 1099 ``pserve`` is a command that reads a :term:`PasteDeploy` ``.ini`` file (e.g.,
1100 ``development.ini``), and configures a server to serve a :app:`Pyramid`
1101 application based on the data in the file.
ef9767 1102
8fe021 1103 ``pserve`` is by no means the only way to start up and serve a :app:`Pyramid`
CM 1104 application.  As we saw in :ref:`firstapp_chapter`, ``pserve`` needn't be
1105 invoked at all to run a :app:`Pyramid` application.  The use of ``pserve`` to
058e90 1106 run a :app:`Pyramid` application is purely conventional based on the output of
e1b26e 1107 its cookiecutter.  But we strongly recommend using ``pserve`` while developing
058e90 1108 your application because many other convenience introspection commands (such as
SP 1109 ``pviews``, ``prequest``, ``proutes``, and others) are also implemented in
1110 terms of configuration availability of this ``.ini`` file format.  It also
b7736b 1111 configures Pyramid logging and provides the ``--reload`` switch for convenient
058e90 1112 restarting of the server when code changes.
aa3306 1113
c3a36b 1114 .. _alternate_wsgi_server:
2c9f3c 1115
c3a36b 1116 Using an Alternate WSGI Server
CM 1117 ------------------------------
1118
e1b26e 1119 Pyramid cookiecutters generate projects which use the :term:`Waitress` WSGI server.
a54e4c 1120 Waitress is a server that is suited for development and light production
SP 1121 usage.  It's not the fastest nor the most featureful WSGI server. Instead, its
1122 main feature is that it works on all platforms that Pyramid needs to run on,
1123 making it a good choice as a default server from the perspective of Pyramid's
1124 developers.
c3a36b 1125
CM 1126 Any WSGI server is capable of running a :app:`Pyramid` application.  But we
a54e4c 1127 suggest you stick with the default server for development, and that you wait to
SP 1128 investigate other server options until you're ready to deploy your application
1129 to production.  Unless for some reason you need to develop on a non-local
1130 system, investigating alternate server options is usually a distraction until
1131 you're ready to deploy.  But we recommend developing using the default
1132 configuration on a local system that you have complete control over; it will
1133 provide the best development experience.
c3a36b 1134
CM 1135 One popular production alternative to the default Waitress server is
ce8894 1136 :term:`mod_wsgi`. You can use ``mod_wsgi`` to serve your :app:`Pyramid` application
a54e4c 1137 using the Apache web server rather than any "pure-Python" server like Waitress.
SP 1138 It is fast and featureful.  See :ref:`modwsgi_tutorial` for details.
c3a36b 1139
CM 1140 Another good production alternative is :term:`Green Unicorn` (aka
a54e4c 1141 ``gunicorn``).  It's faster than Waitress and slightly easier to configure than
ce8894 1142 ``mod_wsgi``, although it depends, in its default configuration, on having a
a54e4c 1143 buffering HTTP proxy in front of it.  It does not, as of this writing, work on
SP 1144 Windows.
1644ef 1145
MM 1146 Automatically Reloading Your Code
1147 ---------------------------------
1148
1149 During development, it can be really useful to automatically have the
1150 webserver restart when you make changes. ``pserve`` has a ``--reload`` switch
1151 to enable this. It uses the
19d341 1152 `hupper <https://docs.pylonsproject.org/projects/hupper/en/latest/>`_ package
1644ef 1153 to enable this behavior. When your code crashes, ``hupper`` will wait for
MM 1154 another change or the ``SIGHUP`` signal before restarting again.
1155
1156 inotify support
1157 ~~~~~~~~~~~~~~~
1158
0aa967 1159 By default ``hupper`` will poll the filesystem for changes to all Python
1644ef 1160 code. This can be pretty inefficient in larger projects. To be nicer to your
MM 1161 hard drive, you should install the
9ce94f 1162 `watchdog <https://pythonhosted.org/watchdog/>`_ package in development.
1644ef 1163 ``hupper`` will automatically use ``watchdog`` to more efficiently poll the
MM 1164 filesystem.
3f1309 1165
MM 1166 Monitoring Custom Files
1167 ~~~~~~~~~~~~~~~~~~~~~~~
1168
1169 By default, ``pserve --reload`` will monitor all imported Python code
1170 (everything in ``sys.modules``) as well as the config file passed to
0aa967 1171 ``pserve`` (e.g., ``development.ini``). You can instruct ``pserve`` to watch
3f1309 1172 other files for changes as well by defining a ``[pserve]`` section in your
MM 1173 configuration file. For example, let's say your application loads the
1174 ``favicon.ico`` file at startup and stores it in memory to efficiently
0aa967 1175 serve it many times. When you change it, you want ``pserve`` to restart:
3f1309 1176
MM 1177 .. code-block:: ini
1178
1179     [pserve]
1180     watch_files =
731a5f 1181         myproject/static/favicon.ico
3f1309 1182
ff0da7 1183 Paths may be absolute or relative to the configuration file. They may also
0aa967 1184 be an :term:`asset specification`. These paths are passed to ``hupper``, which
ff0da7 1185 has some basic support for globbing. Acceptable glob patterns depend on the
MM 1186 version of Python being used.