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