Steve Piercy
2017-06-16 80ce00e7a408fc295d9eb1ffef3cdc6073a01b5e
commit | author | age
e0887e 1 .. index::
CM 2    single: Agendaless Consulting
3    single: Pylons
4    single: Django
5    single: Zope
9ec2d6 6    single: frameworks vs. libraries
CM 7    single: framework
e0887e 8
fd5ae9 9 :app:`Pyramid` Introduction
ca00fb 10 ===========================
9e3bdb 11
719ab3 12 :app:`Pyramid` is a Python web application *framework*. It is designed to make creating web applications easier. It is open source.
9e3bdb 13
66b715 14 .. sidebar:: What Is a Framework?
9ec2d6 15
719ab3 16    A *framework* provides capabilities that developers can enhance or extend. A web application framework provides many of the common needs of building web applications allowing developers to concentrate only on the parts that are specific to their application.
66b715 17
719ab3 18    Every framework makes choices about how a particular problem should be solved. When developers choose to use a framework, they cede control over the portions of their application that are provided by the framework. It is possible to write a complete web application without any framework, by using Python libraries. In practice, however, it is often more practical to use a framework, so long as your chosen framework fits the requirements of your application.
0bc787 19
794fd3 20 :app:`Pyramid` follows these design and engineering principles:
9e3bdb 21
878328 22 Simplicity
719ab3 23    :app:`Pyramid` is designed to be easy to use. You can get started even if you don't understand it all. And when you're ready to do more, :app:`Pyramid` will be there for you.
9e3bdb 24
878328 25 Minimalism
719ab3 26    Out of the box, :app:`Pyramid` provides only the core tools needed for nearly all web applications: mapping URLs to code, security, and serving static assets (files like JavaScript and CSS). Additional tools provide templating, database integration and more. But with :app:`Pyramid` you can *"pay only for what you eat"*.
9e3bdb 27
878328 28 Documentation
9f2b00 29    :app:`Pyramid` is committed to comprehensive and up-to-date documentation.
9e3bdb 30
878328 31 Speed
9f2b00 32   :app:`Pyramid` is designed to be noticeably fast.
9e3bdb 33
b0d207 34 Reliability
719ab3 35   :app:`Pyramid` is developed conservatively and tested exhaustively. Our motto is: "If it ain't tested, it's broke".
878328 36
9ec2d6 37 Openness
719ab3 38   As with Python, the :app:`Pyramid` software is distributed under a `permissive open source license <http://repoze.org/license.html>`_.
3ea7c7 39
7c6809 40 .. _why_pyramid:
C 41
42 Why Pyramid?
43 ------------
44
794fd3 45 In a world filled with web frameworks, why should you choose :app:`Pyramid`\ ?
7c6809 46
C 47 Modern
48 ~~~~~~
49
719ab3 50 :app:`Pyramid` is fully compatible with Python 3. If you develop a :app:`Pyramid` application today, you can rest assured that you'll be able to use the most modern features of your favorite language. And in the years to come, you'll continue to bed working on a framework that is up-to-dateand forward-looking.
7c6809 51
C 52 Tested
53 ~~~~~~
54
719ab3 55 Untested code is broken by design. The :app:`Pyramid` community has a strong testing culture and our framework reflects that. Every release of :app:`Pyramid` has 100% statement coverage (as measured by `coverage <https://coverage.readthedocs.io>`_) and 95% decision/condition coverage. (as measured by `instrumental <http://instrumental.readthedocs.io/en/latest/intro.html>`_) It is automatically tested using `Travis <https://travis-ci.org/Pylons/pyramid>`_ and `Jenkins <http://jenkins.pylonsproject.org/job/pyramid/>`_ on supported versions of Python after each commit to its GitHub repository. `Official Pyramid add-ons <https://trypyramid.com/resources-extending-pyramid.html>`_ are held to a similar testing standard.
7c6809 56
719ab3 57 We still find bugs in :app:`Pyramid`, but we've noticed we find a lot fewer of them while working on projects with a solid testing regime.
7c6809 58
C 59 Documented
60 ~~~~~~~~~~
61
381fe1 62 The :app:`Pyramid` documentation is comprehensive. We strive to keep our narrative documentation both complete and friendly to newcomers. We also maintain the :ref:`Pyramid Community Cookbook <cookbook:pyramid-cookbook>` of  recipes demonstrating common scenarios you might face. Contributions in the form of improvements to our documentation are always appreciated. And we always welcome improvements to our `official tutorials <html_tutorials>`_ as well as new contributions to our `community maintained tutorials <tutorials:pyramid-tutorials>`_.
7c6809 63
C 64 Supported
65 ~~~~~~~~~
66
719ab3 67 You can get help quickly with :app:`Pyramid`. It's our goal that no :app:`Pyramid` question go unanswered. Whether you ask a question on IRC, on the Pylons-discuss mailing list, or on StackOverflow, you're likely to get a reasonably prompt response.
7c6809 68
719ab3 69 :app:`Pyramid` is also a welcoming, friendly space for newcomers. We don't tolerate "support trolls" or those who enjoy berating fellow users in our support channels. We try to keep it well-lit and new-user-friendly.
7c6809 70
981a9d 71 .. seealso::
C 72
719ab3 73     See also our `#pyramid IRC channel <https://webchat.freenode.net/?channels=pyramid>`_, our `pylons-discuss mailing list <https://groups.google.com/forum/#!forum/pylons-discuss>`_, and :ref:`support-and-development`.
7c6809 74
d8fc16 75 .. _what_makes_pyramid_unique:
CM 76
d59239 77 What makes Pyramid unique
bb93cb 78 -------------------------
CM 79
719ab3 80 There are many tools available for web development. What would make someone want to use :app:`Pyramid` instead?  What makes :app:`Pyramid` unique?
bb93cb 81
719ab3 82 With :app:`Pyramid` you can write very small applications without needing to know a lot. And by learning a bit more, you can write very large applications too. :app:`Pyramid` will allow you to become productive quickly, and will grow with you. It won't hold you back when your application is small, and it won't get in your way when your application becomes large. Other application frameworks seem to fall into two non-overlapping categories: those that support "small apps" and those designed for "big apps".
bb93cb 83
719ab3 84 We don't believe you should have to make this choice. You can't really know how large your application will become.  You certainly shouldn't have to rewrite a small application in another framework when it gets "too big". A well-designed framework should be able to be good at both. :app:`Pyramid` is that kind of framework.
bb93cb 85
719ab3 86 :app:`Pyramid` provides a set of features that are unique among Python web frameworks. Others may provide some, but only :app:`Pyramid` provides them all, in one place, fully documented, and *à la carte* without needing to pay for the whole banquet.
f92085 87
bb93cb 88
02c5ba 89 Build single-file applications
C 90 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bb93cb 91
719ab3 92 You can write a :app:`Pyramid` application that lives entirely in one Python file. Such an application is easy to understand since everything is in one place. It is easy to deploy because you don't need to know much about Python packaging. :app:`Pyramid` allows you to do almost everything that so-called *microframeworks* can in very similar ways.
bb93cb 93
d3aae8 94 .. literalinclude:: helloworld.py
bb93cb 95
2033ee 96 .. seealso::
SP 97
98     See also :ref:`firstapp_chapter`.
d3aae8 99
6fcca6 100 Configure applications with decorators
C 101 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bb93cb 102
719ab3 103 :app:`Pyramid` allows you to keep your configuration right next to your code. That way you don't have to switch files to see your configuration. For example:
bdebfb 104
CM 105 .. code-block:: python
106
107    from pyramid.view import view_config
108    from pyramid.response import Response
bb93cb 109
CM 110    @view_config(route_name='fred')
111    def fred_view(request):
112        return Response('fred')
113
719ab3 114 However, using :app:`Pyramid` configuration decorators does not change your code. It remains easy to extend, test, or reuse. You can test your code as if the decorators were not there. You can instruct the framework to ignore some decorators. You can even use an imperative style to write your configuration, skipping decorators entirely.
bb93cb 115
981a9d 116 .. seealso::
C 117
118     See also :ref:`mapping_views_using_a_decorator_section`.
bb93cb 119
dc7c27 120 Generate application URLs
C 121 ~~~~~~~~~~~~~~~~~~~~~~~~~
bb93cb 122
719ab3 123 Dynamic web applications produce URLs that can change depending on what you are viewing. :app:`Pyramid` provides flexible, consistent, easy to use tools for generating URLs. When you use these tools to write your application, you can change your configuration without fear of breaking links in your web pages.
bb93cb 124
981a9d 125 .. seealso::
C 126
127     See also :ref:`generating_route_urls`.
bb93cb 128
8c1255 129 Serve static assets
bb93cb 130 ~~~~~~~~~~~~~~~~~~~
CM 131
719ab3 132 Web applications often require JavaScript, CSS, images and other so-called *static assets*. :app:`Pyramid` provides flexible tools for serving these kinds of files. You can serve them directly from :app:`Pyramid`, or host them on an external server or CDN (content delivery network). Either way, :app:`Pyramid` can help you to generate URLs so you can change where your files come from without changing any code.
bb93cb 133
981a9d 134 .. seealso::
C 135
136     See also :ref:`static_assets_section`.
bb93cb 137
0c4065 138 Develop interactively
C 139 ~~~~~~~~~~~~~~~~~~~~~
daefb5 140
719ab3 141 :app:`Pyramid` can automatically detect changes you make to template files and code, so your changes are immediately available in your browser. You can debug using plain old ``print()`` calls, which will display to your console.
bb93cb 142
719ab3 143 :app:`Pyramid` has a debug toolbar that allows you to see information about how your application is working right in your browser. See configuration, installed packages, SQL queries, logging statements and more.
0c4065 144
719ab3 145 When your application has an error, an interactive debugger allows you to poke around from your browser to find out what happened.
bb93cb 146
719ab3 147 To use the :app:`Pyramid` debug toolbar, build your project with a :app:`Pyramid` :term:`cookiecutter`.
bb93cb 148
981a9d 149 .. seealso::
C 150
151     See also :ref:`debug_toolbar`.
bb93cb 152
0027f5 153 Debug with power
C 154 ~~~~~~~~~~~~~~~~
bb93cb 155
794fd3 156 When things go wrong, :app:`Pyramid` gives you powerful ways to fix the problem.
bb93cb 157
719ab3 158 You can configure :app:`Pyramid` to print helpful information to the console. The ``debug_notfound`` setting shows information about URLs that aren't matched. The ``debug_authorization`` setting provides helpful messages about why you aren't allowed to do what you just tried.
0027f5 159
719ab3 160 :app:`Pyramid` also has command line tools to help you verify your configuration. You can use ``proutes`` and ``pviews`` to inspect how URLs are connected to your application code.
bb93cb 161
981a9d 162 .. seealso::
C 163
164     See also :ref:`debug_authorization_section`, :ref:`command_line_chapter`,
165     and :doc:`../pscripts/index`
bb93cb 166
f9822d 167 Extend your application
C 168 ~~~~~~~~~~~~~~~~~~~~~~~
214125 169
719ab3 170 :app:`Pyramid` add-ons extend the core of the framework with useful abilities. There are add-ons available for your favorite template language, SQL and NoSQL databases, authentication services and more.
f9822d 171
719ab3 172 Supported :app:`Pyramid` add-ons are held to the same demanding standards as the framework itself. You will find them to be fully tested and well documented.
214125 173
981a9d 174 .. seealso::
C 175
176     See also https://trypyramid.com/resources-extending-pyramid.html
214125 177
ff14e5 178 Write your views, *your* way
C 179 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bb93cb 180
719ab3 181 A fundamental task for any framework is to map URLs to code. In :app:`Pyramid`, that code is called a :term:`view callable`. View callables can be functions, class methods or even callable class instances. You are free to choose the approach that best fits your use case. Regardless of your choice, :app:`Pyramid` treats them the same. You can change your mind at any time without any penalty. There are no artificial distinctions between the various approaches.
bb93cb 182
214125 183 Here's a view callable defined as a function:
CM 184
185 .. code-block:: python
186    :linenos:
187
188    from pyramid.response import Response
189    from pyramid.view import view_config
190
191    @view_config(route_name='aview')
192    def aview(request):
193        return Response('one')
194
195 Here's a few views defined as methods of a class instead:
196
197 .. code-block:: python
198    :linenos:
199
200    from pyramid.response import Response
201    from pyramid.view import view_config
202
203    class AView(object):
204        def __init__(self, request):
205            self.request = request
206
207        @view_config(route_name='view_one')
e73a54 208        def view_one(self):
214125 209            return Response('one')
CM 210
211        @view_config(route_name='view_two')
e73a54 212        def view_two(self):
214125 213            return Response('two')
CM 214
2033ee 215 .. seealso::
SP 216
217     See also :ref:`view_config_placement`.
bb93cb 218
82dcba 219 .. _intro_asset_specs:
CM 220
9b942a 221 Find *your* static assets
C 222 ~~~~~~~~~~~~~~~~~~~~~~~~~
82dcba 223
719ab3 224 In many web frameworks, the static assets required by an application are kept in a globally shared location, "the *static* directory". Others use a lookup scheme, like an ordered set of template directories. Both of these approaches have problems when it comes to customization.
82dcba 225
719ab3 226 :app:`Pyramid` takes a different approach. Static assets are located using *asset specifications*, strings that contain reference both to a Python package name and a file or directory name, e.g. ``MyPackage:static/index.html``. These specifications are used for templates, JavaScript and CSS, translation files, and any other package-bound static resource. By using asset specifications, :app:`Pyramid` makes it easy to extend your application with other packages without worrying about conflicts.
9b942a 227
719ab3 228 What happens if another :app:`Pyramid` package you are using provides an asset you need to customize? Maybe that page template needs better HTML, or you want to update some CSS. With asset specifications you can override the assets from other packages using simple wrappers.
82dcba 229
CM 230 Examples: :ref:`asset_specifications` and :ref:`overriding_assets_section`.
231
5404f9 232 Use *your* templates
C 233 ~~~~~~~~~~~~~~~~~~~~
82dcba 234
719ab3 235 In :app:`Pyramid`, the job of creating a ``Response`` belongs to a :term:`renderer`. Any templating system—Mako, Chameleon, Jinja2—can be a renderer. In fact, packages exist for all of these systems. But if you'd rather use another, a structured API exists allowing you to create a renderer using your favorite templating system. You can use the templating system *you* understand, not one required by the framework.
82dcba 236
719ab3 237 What's more, :app:`Pyramid` does not make you use a single templating system exclusively.  You can use multiple templating systems, even in the same project.
82dcba 238
CM 239 Example: :ref:`templates_used_directly`.
240
1610c8 241 Write testable views
C 242 ~~~~~~~~~~~~~~~~~~~~
e08844 243
719ab3 244 When you use a :term:`renderer` with your view callable, you are freed from needing to return a "webby" ``Response`` object. Instead your views can return a simple Python dictionary. :app:`Pyramid` will take care of rendering the information in that dictionary to a ``Response`` on your behalf. As a result, your views are more easily tested, since you don't need to parse HTML to evaluate the results. :app:`Pyramid` makes it a snap to write unit tests for your views, instead of requiring you to use functional tests.
85ac6b 245
1f7a00 246 .. index::
KOP 247    pair: renderer; explicitly calling
248    pair: view renderer; explictly calling
249
250 .. _example_render_to_response_call:
251
719ab3 252 For example, a typical web framework might return a ``Response`` object from a ``render_to_response`` call:
85ac6b 253
CM 254 .. code-block:: python
392a6c 255     :linenos:
85ac6b 256
CM 257     from pyramid.renderers import render_to_response
258
259     def myview(request):
260         return render_to_response('myapp:templates/mytemplate.pt', {'a':1},
261                                   request=request)
262
719ab3 263 While you *can* do this in :app:`Pyramid`, you can also return a Python dictionary:
85ac6b 264
CM 265 .. code-block:: python
392a6c 266     :linenos:
85ac6b 267
CM 268     from pyramid.view import view_config
269
270     @view_config(renderer='myapp:templates/mytemplate.pt')
271     def myview(request):
272         return {'a':1}
e08844 273
719ab3 274 By configuring your view to use a renderer, you tell :app:`Pyramid` to use the ``{'a':1}`` dictionary and the specified template to render a response on your behalf.
1610c8 275
719ab3 276 The string passed as ``renderer=`` above is an :term:`asset specification`. Asset specifications are widely used in :app:`Pyramid`. They allow for more reliable customization. See :ref:`intro_asset_specs` for more information.
d10aeb 277
e08844 278 Example: :ref:`renderers_chapter`.
CM 279
a419bc 280 Use events to coordinate actions
C 281 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bb93cb 282
719ab3 283 When writing web applications, it is often important to have your code run at a specific point in the lifecycle of a request. In :app:`Pyramid`, you can accomplish this using *subscribers* and *events*.
bb93cb 284
719ab3 285 For example, you might have a job that needs to be done each time your application handles a new request. :app:`Pyramid` emits a ``NewRequest`` event at this point in the request handling lifecycle. You can register your code as a subscriber to this event using a clear, declarative style:
7c6809 286
C 287 .. code-block:: python
288
289     from pyramid.events import NewRequest
290     from pyramid.events import subscriber
291
292     @subscriber(NewRequest)
293     def my_job(event):
294         do_something(event.request)
295
719ab3 296 :app:`Pyramid`\ 's event system can be extended as well. If you need, you can create events of your own and send them using :app:`Pyramid`\ 's event system. Then anyone working with your application can subscribe to your events and coordinate their code with yours.
970b88 297
82dcba 298 Example: :ref:`events_chapter` and :ref:`event_types`.
CM 299
7c6809 300 Build international applications
C 301 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
82dcba 302
719ab3 303 :app:`Pyramid` ships with internationalization-related features in its core: localization, pluralization, and creating message catalogs from source files and templates.  :app:`Pyramid` allows for a plurality of message catalogs via the use of translation domains.  You can create a system that has its own translations without conflict with other translations in other domains.
82dcba 304
CM 305 Example: :ref:`i18n_chapter`.
306
7c6809 307 Build efficient applications
C 308 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
82dcba 309
719ab3 310 :app:`Pyramid` provides an easy way to *cache* the results of slow or expensive views. You can indicate in view configuration that you want a view to be cached:
a419bc 311
C 312 .. code-block:: python
82dcba 313
7c6809 314     @view_config(http_cache=3600) # 60 minutes
a419bc 315     def myview(request):
C 316         # ...
82dcba 317
719ab3 318 :app:`Pyramid` will automatically add the appropriate ``Cache-Control`` and ``Expires`` headers to the response it creates.
82dcba 319
719ab3 320 See the :meth:`~pyramid.config.Configurator.add_view` method's ``http_cache`` documentation for more information.
82dcba 321
7c6809 322 Build fast applications
C 323 ~~~~~~~~~~~~~~~~~~~~~~~
82dcba 324
719ab3 325 The :app:`Pyramid` core is fast. It has been engineered from the ground up for speed. It only does as much work as absolutely necessary when you ask it to get a job done. If you need speed from your application, :app:`Pyramid` is the right choice for you.
82dcba 326
d59239 327 Example: http://blog.curiasolutions.com/pages/the-great-web-framework-shootout.html
82dcba 328
7c6809 329 Store session data
C 330 ~~~~~~~~~~~~~~~~~~
82dcba 331
719ab3 332 :app:`Pyramid` has built-in support for HTTP sessions, so you can associate data with specific users between requests. Lots of other frameworks also support sessions. But :app:`Pyramid` allows you to plug in your own custom sessioning system. So long as your system conforms to a documented interface, you can drop it in in place of the provided system.
7c6809 333
719ab3 334 Currently there is a binding package for the third-party Redis sessioning system that does exactly this. But if you have a specialized need (perhaps you want to store your session data in MongoDB), you can.  You can even switch between implementations without changing your application code.
7c6809 335
C 336 Example: :ref:`sessions_chapter`.
337
338 Handle problems with grace
339 ~~~~~~~~~~~~~~~~~~~~~~~~~~
340
719ab3 341 Mistakes happen. Problems crop up. No one writes bug-free code. :app:`Pyramid`provides a way to handle the exceptions your code encounters. An :term:`exception view` is a special kind of view which is automatically called when a particular exception type arises without being handled by your application.
7c6809 342
719ab3 343 For example, you might register an exception view for the :exc:`Exception` exception type, which will catch *all* exceptions, and present a pretty "well, this is embarrassing" page.  Or you might choose to register an exception view for only certain application-specific exceptions. You can make one for when a file is not found, or when the user doesn't have permission to do something. In the former case, you can show a pretty "Not Found" page; in the latter case you might show a login form.
82dcba 344
CM 345 Example: :ref:`exception_views`.
346
7c6809 347 And much, much more...
82dcba 348 ~~~~~~~~~~~~~~~~~~~~~~
CM 349
719ab3 350 :app:`Pyramid` has been built with a number of other sophisticated design features that make it adaptable. Read more about them below.
82dcba 351
7c6809 352 .. toctree::
C 353    :maxdepth: 2
82dcba 354
f20a01 355    advanced-features
bb93cb 356
CM 357
358
359
360
3ea7c7 361 .. index::
6ce1e0 362    single: Pylons Project
3ea7c7 363
a3a27a 364 What Is The Pylons Project?
CM 365 ---------------------------
3ea7c7 366
80ce00 367 :app:`Pyramid` is a member of the collection of software published under the Pylons Project.  Pylons software is written by a loose-knit community of contributors.  The `Pylons Project website <https://pylonsproject.org>`_ includes details about how :app:`Pyramid` relates to the Pylons Project.
093628 368
8c56ae 369 .. index::
fec0f0 370    single: pyramid and other frameworks
e0887e 371    single: Zope
CM 372    single: Pylons
373    single: Django
374    single: MVC
8c56ae 375
fd5ae9 376 :app:`Pyramid` and Other Web Frameworks
f47d22 377 ---------------------------------------
9e3bdb 378
719ab3 379 The first release of :app:`Pyramid`\ 's predecessor (named :mod:`repoze.bfg`) was made in July of 2008.  At the end of 2010, we changed the name of :mod:`repoze.bfg` to :app:`Pyramid`.  It was merged into the Pylons project as :app:`Pyramid` in November of that year.
fec0f0 380
719ab3 381 :app:`Pyramid` was inspired by :term:`Zope`, :term:`Pylons` (version 1.0), and :term:`Django`.  As a result, :app:`Pyramid` borrows several concepts and features from each, combining them into a unique web framework.
878328 382
719ab3 383 Similar to :term:`Zope`, :app:`Pyramid` applications may easily be extended. If you work within the constraints of the framework, you can produce applications that can be reused, modified, or extended without needing to modify the original application code. :app:`Pyramid` also inherits the concepts of :term:`traversal` and declarative security from Zope.
601289 384
719ab3 385 Similar to :term:`Pylons` version 1.0, :app:`Pyramid` is largely free of policy. It makes no assertions about which database or template system you should use. You are free to use whatever third-party components fit the needs of your specific application. :app:`Pyramid` also inherits its approach to :term:`URL dispatch` from Pylons.
601289 386
719ab3 387 Similar to :term:`Django`, :app:`Pyramid` values extensive documentation. In addition, the concept of a :term:`view` is used by :app:`Pyramid` much as it would be by Django.
a56d0c 388
719ab3 389 Other Python web frameworks advertise themselves as members of a class of web frameworks named `model-view-controller <https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller>`_ frameworks. The authors of :app:`Pyramid` do not believe that the MVC pattern fits the web particularly well. However, if this abstraction works for you, :app:`Pyramid` also generally fits into this class.