From 02011f1f5d3fae6eac0209b5faccc06079dd1b41 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Tue, 20 Oct 2015 00:32:14 -0500 Subject: first cut at removing default cache busters --- docs/api/static.rst | 9 ------ docs/narr/assets.rst | 80 +++++++++++++++++++++++----------------------------- 2 files changed, 35 insertions(+), 54 deletions(-) (limited to 'docs') diff --git a/docs/api/static.rst b/docs/api/static.rst index b6b279139..e6d6e4618 100644 --- a/docs/api/static.rst +++ b/docs/api/static.rst @@ -9,17 +9,8 @@ :members: :inherited-members: - .. autoclass:: PathSegmentCacheBuster - :members: - .. autoclass:: QueryStringCacheBuster :members: - .. autoclass:: PathSegmentMd5CacheBuster - :members: - - .. autoclass:: QueryStringMd5CacheBuster - :members: - .. autoclass:: QueryStringConstantCacheBuster :members: diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 020794062..397e0258d 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -372,30 +372,38 @@ assets by passing the optional argument, ``cachebust`` to .. code-block:: python :linenos: + import time + from pyramid.static import QueryStringConstantCacheBuster + # config is an instance of pyramid.config.Configurator - config.add_static_view(name='static', path='mypackage:folder/static', - cachebust=True) + config.add_static_view( + name='static', path='mypackage:folder/static', + cachebust=QueryStringConstantCacheBuster(str(int(time.time()))), + ) Setting the ``cachebust`` argument instructs :app:`Pyramid` to use a cache -busting scheme which adds the md5 checksum for a static asset as a path segment -in the asset's URL: +busting scheme which adds the curent time for a static asset to the query +string in the asset's URL: .. code-block:: python :linenos: js_url = request.static_url('mypackage:folder/static/js/myapp.js') - # Returns: 'http://www.example.com/static/c9658b3c0a314a1ca21e5988e662a09e/js/myapp.js' + # Returns: 'http://www.example.com/static/js/myapp.js?x=1445318121' -When the asset changes, so will its md5 checksum, and therefore so will its -URL. Supplying the ``cachebust`` argument also causes the static view to set -headers instructing clients to cache the asset for ten years, unless the -``cache_max_age`` argument is also passed, in which case that value is used. +When the web server restarts, the time constant will change and therefore so +will its URL. Supplying the ``cachebust`` argument also causes the static +view to set headers instructing clients to cache the asset for ten years, +unless the ``cache_max_age`` argument is also passed, in which case that +value is used. -.. note:: +.. warning:: - md5 checksums are cached in RAM, so if you change a static resource without - restarting your application, you may still generate URLs with a stale md5 - checksum. + Cache busting is an inherently complex topic as it integrates the asset + pipeline and the web application. It is expected and desired that + application authors will write their own cache buster implementations + conforming to the properties of their own asset pipelines. See + :ref:`custom_cache_busters` for information on writing your own. Disabling the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -406,40 +414,21 @@ configured cache busters without changing calls to ``PYRAMID_PREVENT_CACHEBUST`` environment variable or the ``pyramid.prevent_cachebust`` configuration value to a true value. +.. _custom_cache_busters: + Customizing the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Revisiting from the previous section: - -.. code-block:: python - :linenos: +The ``cachebust`` option to +:meth:`~pyramid.config.Configurator.add_static_view` may be set to any object +that implements the interface :class:`~pyramid.interfaces.ICacheBuster`. - # config is an instance of pyramid.config.Configurator - config.add_static_view(name='static', path='mypackage:folder/static', - cachebust=True) - -Setting ``cachebust`` to ``True`` instructs :app:`Pyramid` to use a default -cache busting implementation that should work for many situations. The -``cachebust`` may be set to any object that implements the interface -:class:`~pyramid.interfaces.ICacheBuster`. The above configuration is exactly -equivalent to: - -.. code-block:: python - :linenos: - - from pyramid.static import PathSegmentMd5CacheBuster - - # config is an instance of pyramid.config.Configurator - config.add_static_view(name='static', path='mypackage:folder/static', - cachebust=PathSegmentMd5CacheBuster()) - -:app:`Pyramid` includes a handful of ready to use cache buster implementations: -:class:`~pyramid.static.PathSegmentMd5CacheBuster`, which inserts an md5 -checksum token in the path portion of the asset's URL, -:class:`~pyramid.static.QueryStringMd5CacheBuster`, which adds an md5 checksum -token to the query string of the asset's URL, and +:app:`Pyramid` ships with a very simplistic :class:`~pyramid.static.QueryStringConstantCacheBuster`, which adds an -arbitrary token you provide to the query string of the asset's URL. +arbitrary token you provide to the query string of the asset's URL. This +is almost never what you want in production as it does not allow fine-grained +busting of individual assets. + In order to implement your own cache buster, you can write your own class from scratch which implements the :class:`~pyramid.interfaces.ICacheBuster` @@ -456,15 +445,16 @@ the hash of the currently checked out code: import os import subprocess - from pyramid.static import PathSegmentCacheBuster + from pyramid.static import QueryStringCacheBuster - class GitCacheBuster(PathSegmentCacheBuster): + class GitCacheBuster(QueryStringCacheBuster): """ Assuming your code is installed as a Git checkout, as opposed to an egg from an egg repository like PYPI, you can use this cachebuster to get the current commit's SHA1 to use as the cache bust token. """ - def __init__(self): + def __init__(self, param='x'): + super(GitCacheBuster, self).__init__(param=param) here = os.path.dirname(os.path.abspath(__file__)) self.sha1 = subprocess.check_output( ['git', 'rev-parse', 'HEAD'], -- cgit v1.2.3 From bf564d134846b16271f6c9c1742fc1fd86de71ec Mon Sep 17 00:00:00 2001 From: Naoko Reeves Date: Thu, 5 Nov 2015 13:40:23 -0700 Subject: literalinclude line number was off for Base object --- docs/tutorials/wiki2/basiclayout.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/tutorials/wiki2/basiclayout.rst b/docs/tutorials/wiki2/basiclayout.rst index 80ae4b34e..695d7f15b 100644 --- a/docs/tutorials/wiki2/basiclayout.rst +++ b/docs/tutorials/wiki2/basiclayout.rst @@ -220,7 +220,7 @@ We also need to create a declarative ``Base`` object to use as a base class for our model: .. literalinclude:: src/basiclayout/tutorial/models.py - :lines: 17 + :lines: 18 :language: py Our model classes will inherit from this ``Base`` class so they can be -- cgit v1.2.3 From 857511d2b575ed7d4d7fee9235d94802bc1bb584 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Thu, 5 Nov 2015 17:11:10 -0800 Subject: minor grammar, fix .rst markup, rewrap to 79 columns --- docs/narr/extending.rst | 194 ++++++++++++++++++++++++------------------------ 1 file changed, 95 insertions(+), 99 deletions(-) (limited to 'docs') diff --git a/docs/narr/extending.rst b/docs/narr/extending.rst index 8462a9da7..d28eb341d 100644 --- a/docs/narr/extending.rst +++ b/docs/narr/extending.rst @@ -1,13 +1,13 @@ .. _extending_chapter: -Extending An Existing :app:`Pyramid` Application -=================================================== +Extending an Existing :app:`Pyramid` Application +================================================ -If a :app:`Pyramid` developer has obeyed certain constraints while building -an application, a third party should be able to change the application's -behavior without needing to modify its source code. The behavior of a -:app:`Pyramid` application that obeys certain constraints can be *overridden* -or *extended* without modification. +If a :app:`Pyramid` developer has obeyed certain constraints while building an +application, a third party should be able to change the application's behavior +without needing to modify its source code. The behavior of a :app:`Pyramid` +application that obeys certain constraints can be *overridden* or *extended* +without modification. We'll define some jargon here for the benefit of identifying the parties involved in such an effort. @@ -16,10 +16,10 @@ Developer The original application developer. Integrator - Another developer who wishes to reuse the application written by the - original application developer in an unanticipated context. He may also - wish to modify the original application without changing the original - application's source code. + Another developer who wishes to reuse the application written by the original + application developer in an unanticipated context. They may also wish to + modify the original application without changing the original application's + source code. The Difference Between "Extensible" and "Pluggable" Applications ---------------------------------------------------------------- @@ -27,31 +27,31 @@ The Difference Between "Extensible" and "Pluggable" Applications Other web frameworks, such as :term:`Django`, advertise that they allow developers to create "pluggable applications". They claim that if you create an application in a certain way, it will be integratable in a sensible, -structured way into another arbitrarily-written application or project -created by a third-party developer. +structured way into another arbitrarily-written application or project created +by a third-party developer. :app:`Pyramid`, as a platform, does not claim to provide such a feature. The platform provides no guarantee that you can create an application and package it up such that an arbitrary integrator can use it as a subcomponent in a larger Pyramid application or project. Pyramid does not mandate the constraints necessary for such a pattern to work satisfactorily. Because -Pyramid is not very "opinionated", developers are able to use wildly -different patterns and technologies to build an application. A given Pyramid -application may happen to be reusable by a particular third party integrator, -because the integrator and the original developer may share similar base -technology choices (such as the use of a particular relational database or -ORM). But the same application may not be reusable by a different developer, -because he has made different technology choices which are incompatible with -the original developer's. +Pyramid is not very "opinionated", developers are able to use wildly different +patterns and technologies to build an application. A given Pyramid application +may happen to be reusable by a particular third party integrator because the +integrator and the original developer may share similar base technology choices +(such as the use of a particular relational database or ORM). But the same +application may not be reusable by a different developer, because they have +made different technology choices which are incompatible with the original +developer's. As a result, the concept of a "pluggable application" is left to layers built above Pyramid, such as a "CMS" layer or "application server" layer. Such -layers are apt to provide the necessary "opinions" (such as mandating a -storage layer, a templating system, and a structured, well-documented pattern -of registering that certain URLs map to certain bits of code) which makes the -concept of a "pluggable application" possible. "Pluggable applications", -thus, should not plug into Pyramid itself but should instead plug into a -system written atop Pyramid. +layers are apt to provide the necessary "opinions" (such as mandating a storage +layer, a templating system, and a structured, well-documented pattern of +registering that certain URLs map to certain bits of code) which makes the +concept of a "pluggable application" possible. "Pluggable applications", thus, +should not plug into Pyramid itself but should instead plug into a system +written atop Pyramid. Although it does not provide for "pluggable applications", Pyramid *does* provide a rich set of mechanisms which allows for the extension of a single @@ -64,13 +64,13 @@ Pyramid applications are *extensible*. .. _building_an_extensible_app: -Rules for Building An Extensible Application +Rules for Building an Extensible Application -------------------------------------------- There is only one rule you need to obey if you want to build a maximally extensible :app:`Pyramid` application: as a developer, you should factor any -overrideable :term:`imperative configuration` you've created into functions -which can be used via :meth:`pyramid.config.Configurator.include` rather than +overridable :term:`imperative configuration` you've created into functions +which can be used via :meth:`pyramid.config.Configurator.include`, rather than inlined as calls to methods of a :term:`Configurator` within the ``main`` function in your application's ``__init__.py``. For example, rather than: @@ -84,8 +84,8 @@ function in your application's ``__init__.py``. For example, rather than: config.add_view('myapp.views.view1', name='view1') config.add_view('myapp.views.view2', name='view2') -You should move the calls to ``add_view`` outside of the (non-reusable) -``if __name__ == '__main__'`` block, and into a reusable function: +You should move the calls to ``add_view`` outside of the (non-reusable) ``if +__name__ == '__main__'`` block, and into a reusable function: .. code-block:: python :linenos: @@ -100,13 +100,12 @@ You should move the calls to ``add_view`` outside of the (non-reusable) config.add_view('myapp.views.view1', name='view1') config.add_view('myapp.views.view2', name='view2') -Doing this allows an integrator to maximally reuse the configuration -statements that relate to your application by allowing him to selectively -include or disinclude the configuration functions you've created from an -"override package". +Doing this allows an integrator to maximally reuse the configuration statements +that relate to your application by allowing them to selectively include or +exclude the configuration functions you've created from an "override package". -Alternately, you can use :term:`ZCML` for the purpose of making configuration -extensible and overrideable. :term:`ZCML` declarations that belong to an +Alternatively you can use :term:`ZCML` for the purpose of making configuration +extensible and overridable. :term:`ZCML` declarations that belong to an application can be overridden and extended by integrators as necessary in a similar fashion. If you use only :term:`ZCML` to configure your application, it will automatically be maximally extensible without any manual effort. See @@ -115,16 +114,15 @@ it will automatically be maximally extensible without any manual effort. See Fundamental Plugpoints ~~~~~~~~~~~~~~~~~~~~~~ -The fundamental "plug points" of an application developed using -:app:`Pyramid` are *routes*, *views*, and *assets*. Routes are declarations -made using the :meth:`pyramid.config.Configurator.add_route` method. Views -are declarations made using the :meth:`pyramid.config.Configurator.add_view` -method. Assets are files that are -accessed by :app:`Pyramid` using the :term:`pkg_resources` API such as static -files and templates via a :term:`asset specification`. Other directives and -configurator methods also deal in routes, views, and assets. For example, the -``add_handler`` directive of the ``pyramid_handlers`` package adds a single -route, and some number of views. +The fundamental "plug points" of an application developed using :app:`Pyramid` +are *routes*, *views*, and *assets*. Routes are declarations made using the +:meth:`pyramid.config.Configurator.add_route` method. Views are declarations +made using the :meth:`pyramid.config.Configurator.add_view` method. Assets are +files that are accessed by :app:`Pyramid` using the :term:`pkg_resources` API +such as static files and templates via a :term:`asset specification`. Other +directives and configurator methods also deal in routes, views, and assets. +For example, the ``add_handler`` directive of the ``pyramid_handlers`` package +adds a single route and some number of views. .. index:: single: extending an existing application @@ -133,10 +131,9 @@ Extending an Existing Application --------------------------------- The steps for extending an existing application depend largely on whether the -application does or does not use configuration decorators and/or imperative -code. +application does or does not use configuration decorators or imperative code. -If The Application Has Configuration Decorations +If the Application Has Configuration Decorations ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ You've inherited a :app:`Pyramid` application which you'd like to extend or @@ -155,9 +152,9 @@ registers more views or routes. config.add_view('mypackage.views.myview', name='myview') If you want to *override* configuration in the application, you *may* need to -run :meth:`pyramid.config.Configurator.commit` after performing the scan of -the original package, then add additional configuration that registers more -views or routes which performs overrides. +run :meth:`pyramid.config.Configurator.commit` after performing the scan of the +original package, then add additional configuration that registers more views +or routes which perform overrides. .. code-block:: python :linenos: @@ -170,11 +167,11 @@ views or routes which performs overrides. Once this is done, you should be able to extend or override the application like any other (see :ref:`extending_the_application`). -You can alternately just prevent a :term:`scan` from happening (by omitting -any call to the :meth:`pyramid.config.Configurator.scan` method). This will +You can alternatively just prevent a :term:`scan` from happening by omitting +any call to the :meth:`pyramid.config.Configurator.scan` method. This will cause the decorators attached to objects in the target application to do -nothing. At this point, you will need to convert all the configuration done -in decorators into equivalent imperative configuration or ZCML and add that +nothing. At this point, you will need to convert all the configuration done in +decorators into equivalent imperative configuration or ZCML, and add that configuration or ZCML to a separate Python package as described in :ref:`extending_the_application`. @@ -183,37 +180,37 @@ configuration or ZCML to a separate Python package as described in Extending the Application ~~~~~~~~~~~~~~~~~~~~~~~~~ -To extend or override the behavior of an existing application, you will need -to create a new package which includes the configuration of the old package, -and you'll perhaps need to create implementations of the types of things -you'd like to override (such as views), which are referred to within the -original package. +To extend or override the behavior of an existing application, you will need to +create a new package which includes the configuration of the old package, and +you'll perhaps need to create implementations of the types of things you'd like +to override (such as views), to which they are referred within the original +package. -The general pattern for extending an existing application looks something -like this: +The general pattern for extending an existing application looks something like +this: - Create a new Python package. The easiest way to do this is to create a new :app:`Pyramid` application using the scaffold mechanism. See :ref:`creating_a_project` for more information. -- In the new package, create Python files containing views and other - overridden elements, such as templates and static assets as necessary. +- In the new package, create Python files containing views and other overridden + elements, such as templates and static assets as necessary. - Install the new package into the same Python environment as the original - application (e.g. ``$VENV/bin/python setup.py develop`` or + application (e.g., ``$VENV/bin/python setup.py develop`` or ``$VENV/bin/python setup.py install``). - Change the ``main`` function in the new package's ``__init__.py`` to include the original :app:`Pyramid` application's configuration functions via :meth:`pyramid.config.Configurator.include` statements or a :term:`scan`. -- Wire the new views and assets created in the new package up using - imperative registrations within the ``main`` function of the - ``__init__.py`` file of the new application. This wiring should happen - *after* including the configuration functions of the old application. - These registrations will extend or override any registrations performed by - the original application. See :ref:`overriding_views`, - :ref:`overriding_routes` and :ref:`overriding_resources`. +- Wire the new views and assets created in the new package up using imperative + registrations within the ``main`` function of the ``__init__.py`` file of the + new application. This wiring should happen *after* including the + configuration functions of the old application. These registrations will + extend or override any registrations performed by the original application. + See :ref:`overriding_views`, :ref:`overriding_routes`, and + :ref:`overriding_resources`. .. index:: pair: overriding; views @@ -221,17 +218,17 @@ like this: .. _overriding_views: Overriding Views -~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~ -The :term:`view configuration` declarations you make which *override* +The :term:`view configuration` declarations that you make which *override* application behavior will usually have the same :term:`view predicate` -attributes as the original you wish to override. These ```` -declarations will point at "new" view code, in the override package you've -created. The new view code itself will usually be cut-n-paste copies of view -callables from the original application with slight tweaks. +attributes as the original that you wish to override. These ```` +declarations will point at "new" view code in the override package that you've +created. The new view code itself will usually be copy-and-paste copies of +view callables from the original application with slight tweaks. -For example, if the original application has the following -``configure_views`` configuration method: +For example, if the original application has the following ``configure_views`` +configuration method: .. code-block:: python :linenos: @@ -254,13 +251,13 @@ configuration function: config.include(configure_views) config.add_view('theoverrideapp.views.theview', name='theview') -In this case, the ``theoriginalapp.views.theview`` view will never be -executed. Instead, a new view, ``theoverrideapp.views.theview`` will be -executed instead, when request circumstances dictate. +In this case, the ``theoriginalapp.views.theview`` view will never be executed. +Instead, a new view, ``theoverrideapp.views.theview`` will be executed when +request circumstances dictate. A similar pattern can be used to *extend* the application with ``add_view`` -declarations. Just register a new view against some other set of predicates -to make sure the URLs it implies are available on some other page rendering. +declarations. Just register a new view against some other set of predicates to +make sure the URLs it implies are available on some other page rendering. .. index:: pair: overriding; routes @@ -270,13 +267,13 @@ to make sure the URLs it implies are available on some other page rendering. Overriding Routes ~~~~~~~~~~~~~~~~~ -Route setup is currently typically performed in a sequence of ordered calls -to :meth:`~pyramid.config.Configurator.add_route`. Because these calls are +Route setup is currently typically performed in a sequence of ordered calls to +:meth:`~pyramid.config.Configurator.add_route`. Because these calls are ordered relative to each other, and because this ordering is typically important, you should retain their relative ordering when performing an -override. Typically, this means *copying* all the ``add_route`` statements -into the override package's file and changing them as necessary. Then -disinclude any ``add_route`` statements from the original application. +override. Typically this means *copying* all the ``add_route`` statements into +the override package's file and changing them as necessary. Then exclude any +``add_route`` statements from the original application. .. index:: pair: overriding; assets @@ -288,9 +285,8 @@ Overriding Assets Assets are files on the filesystem that are accessible within a Python *package*. An entire chapter is devoted to assets: :ref:`assets_chapter`. -Within this chapter is a section named :ref:`overriding_assets_section`. -This section of that chapter describes in detail how to override package -assets with other assets by using the -:meth:`pyramid.config.Configurator.override_asset` method. Add such -``override_asset`` calls to your override package's ``__init__.py`` to -perform overrides. +Within this chapter is a section named :ref:`overriding_assets_section`. This +section of that chapter describes in detail how to override package assets with +other assets by using the :meth:`pyramid.config.Configurator.override_asset` +method. Add such ``override_asset`` calls to your override package's +``__init__.py`` to perform overrides. -- cgit v1.2.3 From 8bb97b9894a3a038b3daa3880c5ea51a1cb8209e Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Thu, 5 Nov 2015 17:57:31 -0800 Subject: reorder, remove redundant statements, reduce verbosity, update headings, rewrap --- docs/index.rst | 149 +++++++++++++++++++++++++++++---------------------------- 1 file changed, 76 insertions(+), 73 deletions(-) (limited to 'docs') diff --git a/docs/index.rst b/docs/index.rst index 0ee3557bf..70e0948f9 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -4,10 +4,9 @@ The Pyramid Web Framework ========================= -:app:`Pyramid` is a small, fast, down-to-earth Python web framework. It -is developed as part of the `Pylons Project -`_. It is licensed under a `BSD-like license -`_. +:app:`Pyramid` is a small, fast, down-to-earth Python web framework. It is +developed as part of the `Pylons Project `_. +It is licensed under a `BSD-like license `_. Here is one of the simplest :app:`Pyramid` applications you can make: @@ -15,30 +14,17 @@ Here is one of the simplest :app:`Pyramid` applications you can make: After you install :app:`Pyramid` and run this application, when you visit ``_ in a browser, you will see the text -``Hello, world!`` +``Hello, world!`` See :ref:`firstapp_chapter` for a full explanation of how +this application works. -See :ref:`firstapp_chapter` for a full explanation of how this application -works. Read the :ref:`html_narrative_documentation` to understand how -:app:`Pyramid` is designed to scale from simple applications like this to -very large web applications. To just dive in headfirst, read the -:doc:`quick_tour`. - -Front Matter -============ - -.. toctree:: - :maxdepth: 1 - - copyright.rst - conventions.rst .. _html_getting_started: Getting Started =============== -If you are new to Pyramid, we have a few resources that can help you get -up to speed right away. +If you are new to Pyramid, we have a few resources that can help you get up to +speed right away. .. toctree:: :hidden: @@ -46,26 +32,65 @@ up to speed right away. quick_tour quick_tutorial/index -* :doc:`quick_tour` goes through the major features in Pyramid, covering - a little about a lot. +* :doc:`quick_tour` gives an overview of the major features in Pyramid, + covering a little about a lot. -* :doc:`quick_tutorial/index` does the same, but in a tutorial format: - deeper treatment of each topic and with working code. +* :doc:`quick_tutorial/index` is similar to the Quick Tour, but in a tutorial + format, with somewhat deeper treatment of each topic and with working code. -* To see a minimal Pyramid web application, check out - :ref:`firstapp_chapter`. +* Like learning by example? Visit the official :ref:`html_tutorials` as well as + the community-contributed :ref:`Pyramid tutorials + `, which include a :ref:`Todo List Application + in One File `. -* For help getting Pyramid set up, try - :ref:`installing_chapter`. +* For help getting Pyramid set up, try :ref:`installing_chapter`. -* Like learning by example? Visit the official - :doc:`wiki tutorial <../tutorials/wiki2/index>` as well as the - community-contributed - :ref:`Pyramid tutorials `, which include - a :ref:`single file tasks tutorial `. +* Need help? See :ref:`Support and Development `. -* Need help? See :ref:`Support and - Development `. + +.. _html_tutorials: + +Tutorials +========= + +Official tutorials explaining how to use :app:`Pyramid` to build various types +of applications, and how to deploy :app:`Pyramid` applications to various +platforms. + +.. toctree:: + :maxdepth: 1 + + tutorials/wiki2/index.rst + tutorials/wiki/index.rst + tutorials/modwsgi/index.rst + + +.. _support-and-development: + +Support and Development +======================= + +The `Pylons Project web site `_ is the main online +source of :app:`Pyramid` support and development information. + +To report bugs, use the `issue tracker +`_. + +If you've got questions that aren't answered by this documentation, contact the +`Pylons-discuss maillist `_ or +join the `#pyramid IRC channel `_. + +Browse and check out tagged and trunk versions of :app:`Pyramid` via the +`Pyramid GitHub repository `_. To check out +the trunk via ``git``, use this command: + +.. code-block:: text + + git clone git@github.com:Pylons/pyramid.git + +To find out how to become a contributor to :app:`Pyramid`, please see the +`contributor's section of the documentation +`_. .. _html_narrative_documentation: @@ -73,8 +98,7 @@ up to speed right away. Narrative Documentation ======================= -Narrative documentation in chapter form explaining how to use -:app:`Pyramid`. +Narrative documentation in chapter form explaining how to use :app:`Pyramid`. .. toctree:: :maxdepth: 2 @@ -119,26 +143,12 @@ Narrative documentation in chapter form explaining how to use narr/threadlocals narr/zca -.. _html_tutorials: - -Tutorials -========= - -Tutorials explaining how to use :app:`Pyramid` to build various types of -applications, and how to deploy :app:`Pyramid` applications to various -platforms. - -.. toctree:: - :maxdepth: 2 - - tutorials/wiki2/index.rst - tutorials/wiki/index.rst - tutorials/modwsgi/index.rst API Documentation ================= -Comprehensive reference material for every public API exposed by :app:`Pyramid`: +Comprehensive reference material for every public API exposed by +:app:`Pyramid`: .. toctree:: :maxdepth: 1 @@ -147,6 +157,7 @@ Comprehensive reference material for every public API exposed by :app:`Pyramid`: api/index api/* + Change History ============== @@ -162,6 +173,7 @@ Change History whatsnew-1.0 changes + Design Documents ================ @@ -170,33 +182,24 @@ Design Documents designdefense -.. _support-and-development: -Support and Development -======================= +Copyright, Trademarks, and Attributions +======================================= -The `Pylons Project web site `_ is the main online -source of :app:`Pyramid` support and development information. +.. toctree:: + :maxdepth: 1 -To report bugs, use the `issue tracker -`_. + copyright -If you've got questions that aren't answered by this documentation, -contact the `Pylons-discuss maillist -`_ or join the `#pyramid -IRC channel `_. -Browse and check out tagged and trunk versions of :app:`Pyramid` via -the `Pyramid GitHub repository `_. -To check out the trunk via ``git``, use this command: +Typographical Conventions +========================= -.. code-block:: text +.. toctree:: + :maxdepth: 1 - git clone git@github.com:Pylons/pyramid.git + conventions -To find out how to become a contributor to :app:`Pyramid`, please see the -`contributor's section of the documentation -`_. Index and Glossary ================== -- cgit v1.2.3 From 1205ecbbb4e131b8eed0616a25e44cd3398b7a0f Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 6 Nov 2015 00:05:11 -0800 Subject: minor grammar, fix .rst markup, add emphasize lines for diff, rewrap to 79 columns --- docs/narr/advconfig.rst | 133 +++++++++++++++++++++++------------------------- 1 file changed, 65 insertions(+), 68 deletions(-) (limited to 'docs') diff --git a/docs/narr/advconfig.rst b/docs/narr/advconfig.rst index 9ceaaa495..ba9bd1352 100644 --- a/docs/narr/advconfig.rst +++ b/docs/narr/advconfig.rst @@ -6,12 +6,11 @@ Advanced Configuration ====================== -To support application extensibility, the :app:`Pyramid` -:term:`Configurator`, by default, detects configuration conflicts and allows -you to include configuration imperatively from other packages or modules. It -also, by default, performs configuration in two separate phases. This allows -you to ignore relative configuration statement ordering in some -circumstances. +To support application extensibility, the :app:`Pyramid` :term:`Configurator` +by default detects configuration conflicts and allows you to include +configuration imperatively from other packages or modules. It also by default +performs configuration in two separate phases. This allows you to ignore +relative configuration statement ordering in some circumstances. .. index:: pair: configuration; conflict detection @@ -70,11 +69,11 @@ try to add another view to the configuration with the same set of server = make_server('0.0.0.0', 8080, app) server.serve_forever() -The application now has two conflicting view configuration statements. When -we try to start it again, it won't start. Instead, we'll receive a traceback -that ends something like this: +The application now has two conflicting view configuration statements. When we +try to start it again, it won't start. Instead we'll receive a traceback that +ends something like this: -.. code-block:: guess +.. code-block:: text :linenos: Traceback (most recent call last): @@ -94,19 +93,19 @@ that ends something like this: This traceback is trying to tell us: -- We've got conflicting information for a set of view configuration - statements (The ``For:`` line). +- We've got conflicting information for a set of view configuration statements + (The ``For:`` line). - There are two statements which conflict, shown beneath the ``For:`` line: ``config.add_view(hello_world. 'hello')`` on line 14 of ``app.py``, and ``config.add_view(goodbye_world, 'hello')`` on line 17 of ``app.py``. -These two configuration statements are in conflict because we've tried to -tell the system that the set of :term:`predicate` values for both view +These two configuration statements are in conflict because we've tried to tell +the system that the set of :term:`predicate` values for both view configurations are exactly the same. Both the ``hello_world`` and ``goodbye_world`` views are configured to respond under the same set of -circumstances. This circumstance: the :term:`view name` (represented by the -``name=`` predicate) is ``hello``. +circumstances. This circumstance, the :term:`view name` represented by the +``name=`` predicate, is ``hello``. This presents an ambiguity that :app:`Pyramid` cannot resolve. Rather than allowing the circumstance to go unreported, by default Pyramid raises a @@ -138,8 +137,7 @@ made by your application. Use the detail provided in the modify your configuration code accordingly. If you're getting a conflict while trying to extend an existing application, -and that application has a function which performs configuration like this -one: +and that application has a function which performs configuration like this one: .. code-block:: python :linenos: @@ -147,8 +145,8 @@ one: def add_routes(config): config.add_route(...) -Don't call this function directly with ``config`` as an argument. Instead, -use :meth:`pyramid.config.Configurator.include`: +Don't call this function directly with ``config`` as an argument. Instead, use +:meth:`pyramid.config.Configurator.include`: .. code-block:: python :linenos: @@ -156,9 +154,9 @@ use :meth:`pyramid.config.Configurator.include`: config.include(add_routes) Using :meth:`~pyramid.config.Configurator.include` instead of calling the -function directly provides a modicum of automated conflict resolution, with -the configuration statements you define in the calling code overriding those -of the included function. +function directly provides a modicum of automated conflict resolution, with the +configuration statements you define in the calling code overriding those of the +included function. .. seealso:: @@ -169,10 +167,10 @@ Using ``config.commit()`` +++++++++++++++++++++++++ You can manually commit a configuration by using the -:meth:`~pyramid.config.Configurator.commit` method between configuration -calls. For example, we prevent conflicts from occurring in the application -we examined previously as the result of adding a ``commit``. Here's the -application that generates conflicts: +:meth:`~pyramid.config.Configurator.commit` method between configuration calls. +For example, we prevent conflicts from occurring in the application we examined +previously as the result of adding a ``commit``. Here's the application that +generates conflicts: .. code-block:: python :linenos: @@ -199,11 +197,12 @@ application that generates conflicts: server = make_server('0.0.0.0', 8080, app) server.serve_forever() -We can prevent the two ``add_view`` calls from conflicting by issuing a call -to :meth:`~pyramid.config.Configurator.commit` between them: +We can prevent the two ``add_view`` calls from conflicting by issuing a call to +:meth:`~pyramid.config.Configurator.commit` between them: .. code-block:: python :linenos: + :emphasize-lines: 16 from wsgiref.simple_server import make_server from pyramid.config import Configurator @@ -230,21 +229,20 @@ to :meth:`~pyramid.config.Configurator.commit` between them: server.serve_forever() In the above example we've issued a call to -:meth:`~pyramid.config.Configurator.commit` between the two ``add_view`` -calls. :meth:`~pyramid.config.Configurator.commit` will execute any pending +:meth:`~pyramid.config.Configurator.commit` between the two ``add_view`` calls. +:meth:`~pyramid.config.Configurator.commit` will execute any pending configuration statements. Calling :meth:`~pyramid.config.Configurator.commit` is safe at any time. It -executes all pending configuration actions and leaves the configuration -action list "clean". +executes all pending configuration actions and leaves the configuration action +list "clean". -Note that :meth:`~pyramid.config.Configurator.commit` has no effect when -you're using an *autocommitting* configurator (see -:ref:`autocommitting_configurator`). +Note that :meth:`~pyramid.config.Configurator.commit` has no effect when you're +using an *autocommitting* configurator (see :ref:`autocommitting_configurator`). .. _autocommitting_configurator: -Using An Autocommitting Configurator +Using an Autocommitting Configurator ++++++++++++++++++++++++++++++++++++ You can also use a heavy hammer to circumvent conflict detection by using a @@ -278,17 +276,17 @@ Automatic Conflict Resolution If your code uses the :meth:`~pyramid.config.Configurator.include` method to include external configuration, some conflicts are automatically resolved. Configuration statements that are made as the result of an "include" will be -overridden by configuration statements that happen within the caller of -the "include" method. +overridden by configuration statements that happen within the caller of the +"include" method. -Automatic conflict resolution supports this goal: if a user wants to reuse a +Automatic conflict resolution supports this goal. If a user wants to reuse a Pyramid application, and they want to customize the configuration of this application without hacking its code "from outside", they can "include" a configuration function from the package and override only some of its configuration statements within the code that does the include. No conflicts will be generated by configuration statements within the code that does the -including, even if configuration statements in the included code would -conflict if it was moved "up" to the calling code. +including, even if configuration statements in the included code would conflict +if it was moved "up" to the calling code. Methods Which Provide Conflict Detection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -312,9 +310,9 @@ These are the methods of the configurator which provide conflict detection: :meth:`~pyramid.config.Configurator.add_resource_url_adapter`, and :meth:`~pyramid.config.Configurator.add_response_adapter`. -:meth:`~pyramid.config.Configurator.add_static_view` also indirectly -provides conflict detection, because it's implemented in terms of the -conflict-aware ``add_route`` and ``add_view`` methods. +:meth:`~pyramid.config.Configurator.add_static_view` also indirectly provides +conflict detection, because it's implemented in terms of the conflict-aware +``add_route`` and ``add_view`` methods. .. index:: pair: configuration; including from external sources @@ -324,10 +322,10 @@ conflict-aware ``add_route`` and ``add_view`` methods. Including Configuration from External Sources --------------------------------------------- -Some application programmers will factor their configuration code in such a -way that it is easy to reuse and override configuration statements. For -example, such a developer might factor out a function used to add routes to -his application: +Some application programmers will factor their configuration code in such a way +that it is easy to reuse and override configuration statements. For example, +such a developer might factor out a function used to add routes to their +application: .. code-block:: python :linenos: @@ -335,8 +333,8 @@ his application: def add_routes(config): config.add_route(...) -Rather than calling this function directly with ``config`` as an argument. -Instead, use :meth:`pyramid.config.Configurator.include`: +Rather than calling this function directly with ``config`` as an argument, +instead use :meth:`pyramid.config.Configurator.include`: .. code-block:: python :linenos: @@ -363,21 +361,21 @@ the special name ``includeme``, which should perform configuration (like the :meth:`~pyramid.config.Configurator.include` can also accept a :term:`dotted Python name` to a function or a module. -.. note: See :ref:`the_include_tag` for a declarative alternative to - the :meth:`~pyramid.config.Configurator.include` method. +.. note:: See :ref:`the_include_tag` for a declarative alternative to the + :meth:`~pyramid.config.Configurator.include` method. .. _twophase_config: Two-Phase Configuration ----------------------- -When a non-autocommitting :term:`Configurator` is used to do configuration -(the default), configuration execution happens in two phases. In the first -phase, "eager" configuration actions (actions that must happen before all -others, such as registering a renderer) are executed, and *discriminators* -are computed for each of the actions that depend on the result of the eager -actions. In the second phase, the discriminators of all actions are compared -to do conflict detection. +When a non-autocommitting :term:`Configurator` is used to do configuration (the +default), configuration execution happens in two phases. In the first phase, +"eager" configuration actions (actions that must happen before all others, such +as registering a renderer) are executed, and *discriminators* are computed for +each of the actions that depend on the result of the eager actions. In the +second phase, the discriminators of all actions are compared to do conflict +detection. Due to this, for configuration methods that have no internal ordering constraints, execution order of configuration method calls is not important. @@ -401,15 +399,14 @@ Has the same result as: config.add_view('some.view', renderer='path_to_custom/renderer.rn') Even though the view statement depends on the registration of a custom -renderer, due to two-phase configuration, the order in which the -configuration statements are issued is not important. ``add_view`` will be -able to find the ``.rn`` renderer even if ``add_renderer`` is called after -``add_view``. +renderer, due to two-phase configuration, the order in which the configuration +statements are issued is not important. ``add_view`` will be able to find the +``.rn`` renderer even if ``add_renderer`` is called after ``add_view``. The same is untrue when you use an *autocommitting* configurator (see :ref:`autocommitting_configurator`). When an autocommitting configurator is -used, two-phase configuration is disabled, and configuration statements must -be ordered in dependency order. +used, two-phase configuration is disabled, and configuration statements must be +ordered in dependency order. Some configuration methods, such as :meth:`~pyramid.config.Configurator.add_route` have internal ordering @@ -420,7 +417,7 @@ added in configuration execution order. More Information ---------------- -For more information, see the article, `"A Whirlwind Tour of Advanced +For more information, see the article `"A Whirlwind Tour of Advanced Configuration Tactics" -`_, +`_ in the Pyramid Cookbook. -- cgit v1.2.3 From 6bc1bb06dd07e34a2f26cbb26bca6fc7a933b881 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 6 Nov 2015 00:55:11 -0800 Subject: minor grammar, fix .rst markup, insert versionchanged directive, rewrap to 79 columns --- docs/narr/extconfig.rst | 266 ++++++++++++++++++++++++------------------------ 1 file changed, 132 insertions(+), 134 deletions(-) (limited to 'docs') diff --git a/docs/narr/extconfig.rst b/docs/narr/extconfig.rst index a61eca7b7..5a46c8b9e 100644 --- a/docs/narr/extconfig.rst +++ b/docs/narr/extconfig.rst @@ -7,9 +7,9 @@ Extending Pyramid Configuration =============================== Pyramid allows you to extend its Configurator with custom directives. Custom -directives can use other directives, they can add a custom :term:`action`, -they can participate in :term:`conflict resolution`, and they can provide -some number of :term:`introspectable` objects. +directives can use other directives, they can add a custom :term:`action`, they +can participate in :term:`conflict resolution`, and they can provide some +number of :term:`introspectable` objects. .. index:: single: add_directive @@ -20,18 +20,17 @@ some number of :term:`introspectable` objects. Adding Methods to the Configurator via ``add_directive`` -------------------------------------------------------- -Framework extension writers can add arbitrary methods to a -:term:`Configurator` by using the -:meth:`pyramid.config.Configurator.add_directive` method of the configurator. -Using :meth:`~pyramid.config.Configurator.add_directive` makes it possible to -extend a Pyramid configurator in arbitrary ways, and allows it to perform -application-specific tasks more succinctly. +Framework extension writers can add arbitrary methods to a :term:`Configurator` +by using the :meth:`pyramid.config.Configurator.add_directive` method of the +configurator. Using :meth:`~pyramid.config.Configurator.add_directive` makes it +possible to extend a Pyramid configurator in arbitrary ways, and allows it to +perform application-specific tasks more succinctly. The :meth:`~pyramid.config.Configurator.add_directive` method accepts two -positional arguments: a method name and a callable object. The callable -object is usually a function that takes the configurator instance as its -first argument and accepts other arbitrary positional and keyword arguments. -For example: +positional arguments: a method name and a callable object. The callable object +is usually a function that takes the configurator instance as its first +argument and accepts other arbitrary positional and keyword arguments. For +example: .. code-block:: python :linenos: @@ -48,8 +47,8 @@ For example: add_newrequest_subscriber) Once :meth:`~pyramid.config.Configurator.add_directive` is called, a user can -then call the added directive by its given name as if it were a built-in -method of the Configurator: +then call the added directive by its given name as if it were a built-in method +of the Configurator: .. code-block:: python :linenos: @@ -59,9 +58,9 @@ method of the Configurator: config.add_newrequest_subscriber(mysubscriber) -A call to :meth:`~pyramid.config.Configurator.add_directive` is often -"hidden" within an ``includeme`` function within a "frameworky" package meant -to be included as per :ref:`including_configuration` via +A call to :meth:`~pyramid.config.Configurator.add_directive` is often "hidden" +within an ``includeme`` function within a "frameworky" package meant to be +included as per :ref:`including_configuration` via :meth:`~pyramid.config.Configurator.include`. For example, if you put this code in a package named ``pyramid_subscriberhelpers``: @@ -72,8 +71,8 @@ code in a package named ``pyramid_subscriberhelpers``: config.add_directive('add_newrequest_subscriber', add_newrequest_subscriber) -The user of the add-on package ``pyramid_subscriberhelpers`` would then be -able to install it and subsequently do: +The user of the add-on package ``pyramid_subscriberhelpers`` would then be able +to install it and subsequently do: .. code-block:: python :linenos: @@ -91,13 +90,12 @@ Using ``config.action`` in a Directive If a custom directive can't do its work exclusively in terms of existing configurator methods (such as -:meth:`pyramid.config.Configurator.add_subscriber`, as above), the directive -may need to make use of the :meth:`pyramid.config.Configurator.action` -method. This method adds an entry to the list of "actions" that Pyramid will -attempt to process when :meth:`pyramid.config.Configurator.commit` is called. -An action is simply a dictionary that includes a :term:`discriminator`, -possibly a callback function, and possibly other metadata used by Pyramid's -action system. +:meth:`pyramid.config.Configurator.add_subscriber` as above), the directive may +need to make use of the :meth:`pyramid.config.Configurator.action` method. This +method adds an entry to the list of "actions" that Pyramid will attempt to +process when :meth:`pyramid.config.Configurator.commit` is called. An action is +simply a dictionary that includes a :term:`discriminator`, possibly a callback +function, and possibly other metadata used by Pyramid's action system. Here's an example directive which uses the "action" method: @@ -122,15 +120,15 @@ closure function named ``register`` is passed as the second argument named When the :meth:`~pyramid.config.Configurator.action` method is called, it appends an action to the list of pending configuration actions. All pending -actions with the same discriminator value are potentially in conflict with -one another (see :ref:`conflict_detection`). When the +actions with the same discriminator value are potentially in conflict with one +another (see :ref:`conflict_detection`). When the :meth:`~pyramid.config.Configurator.commit` method of the Configurator is called (either explicitly or as the result of calling :meth:`~pyramid.config.Configurator.make_wsgi_app`), conflicting actions are -potentially automatically resolved as per -:ref:`automatic_conflict_resolution`. If a conflict cannot be automatically -resolved, a :exc:`pyramid.exceptions.ConfigurationConflictError` is raised -and application startup is prevented. +potentially automatically resolved as per :ref:`automatic_conflict_resolution`. +If a conflict cannot be automatically resolved, a +:exc:`pyramid.exceptions.ConfigurationConflictError` is raised and application +startup is prevented. In our above example, therefore, if a consumer of our ``add_jammyjam`` directive did this: @@ -146,14 +144,14 @@ generated by the two calls are in direct conflict. Automatic conflict resolution cannot resolve the conflict (because no ``config.include`` is involved), and the user provided no intermediate :meth:`pyramid.config.Configurator.commit` call between the calls to -``add_jammyjam`` to ensure that the successive calls did not conflict with -each other. +``add_jammyjam`` to ensure that the successive calls did not conflict with each +other. This demonstrates the purpose of the discriminator argument to the action method: it's used to indicate a uniqueness constraint for an action. Two actions with the same discriminator will conflict unless the conflict is -automatically or manually resolved. A discriminator can be any hashable -object, but it is generally a string or a tuple. *You use a discriminator to +automatically or manually resolved. A discriminator can be any hashable object, +but it is generally a string or a tuple. *You use a discriminator to declaratively ensure that the user doesn't provide ambiguous configuration statements.* @@ -169,21 +167,20 @@ appended to the pending actions list. When the pending configuration actions are processed during :meth:`~pyramid.config.Configurator.commit`, and no conflicts occur, the *callable* provided as the second argument to the :meth:`~pyramid.config.Configurator.action` method within ``add_jammyjam`` is -called with no arguments. The callable in ``add_jammyjam`` is the -``register`` closure function. It simply sets the value -``config.registry.jammyjam`` to whatever the user passed in as the -``jammyjam`` argument to the ``add_jammyjam`` function. Therefore, the -result of the user's call to our directive will set the ``jammyjam`` -attribute of the registry to the string ``first``. *A callable is used by a -directive to defer the result of a user's call to the directive until -conflict detection has had a chance to do its job*. +called with no arguments. The callable in ``add_jammyjam`` is the ``register`` +closure function. It simply sets the value ``config.registry.jammyjam`` to +whatever the user passed in as the ``jammyjam`` argument to the +``add_jammyjam`` function. Therefore, the result of the user's call to our +directive will set the ``jammyjam`` attribute of the registry to the string +``first``. *A callable is used by a directive to defer the result of a user's +call to the directive until conflict detection has had a chance to do its job*. Other arguments exist to the :meth:`~pyramid.config.Configurator.action` -method, including ``args``, ``kw``, ``order``, and ``introspectables``. +method, including ``args``, ``kw``, ``order``, and ``introspectables``. -``args`` and ``kw`` exist as values, which, if passed, will be used as -arguments to the ``callable`` function when it is called back. For example -our directive might use them like so: +``args`` and ``kw`` exist as values, which if passed will be used as arguments +to the ``callable`` function when it is called back. For example, our +directive might use them like so: .. code-block:: python :linenos: @@ -198,31 +195,34 @@ our directive might use them like so: In the above example, when this directive is used to generate an action, and that action is committed, ``config.registry.jammyjam_args`` will be set to ``('one',)`` and ``config.registry.jammyjam_kw`` will be set to -``{'two':'two'}``. ``args`` and ``kw`` are honestly not very useful when -your ``callable`` is a closure function, because you already usually have -access to every local in the directive without needing them to be passed -back. They can be useful, however, if you don't use a closure as a callable. +``{'two':'two'}``. ``args`` and ``kw`` are honestly not very useful when your +``callable`` is a closure function, because you already usually have access to +every local in the directive without needing them to be passed back. They can +be useful, however, if you don't use a closure as a callable. ``order`` is a crude order control mechanism. ``order`` defaults to the integer ``0``; it can be set to any other integer. All actions that share an order will be called before other actions that share a higher order. This makes it possible to write a directive with callable logic that relies on the -execution of the callable of another directive being done first. For -example, Pyramid's :meth:`pyramid.config.Configurator.add_view` directive -registers an action with a higher order than the +execution of the callable of another directive being done first. For example, +Pyramid's :meth:`pyramid.config.Configurator.add_view` directive registers an +action with a higher order than the :meth:`pyramid.config.Configurator.add_route` method. Due to this, the -``add_view`` method's callable can assume that, if a ``route_name`` was -passed to it, that a route by this name was already registered by -``add_route``, and if such a route has not already been registered, it's a -configuration error (a view that names a nonexistent route via its -``route_name`` parameter will never be called). As of Pyramid 1.6 it is -possible for one action to invoke another. See :ref:`ordering_actions` for -more information. - -``introspectables`` is a sequence of :term:`introspectable` objects. You can -pass a sequence of introspectables to the -:meth:`~pyramid.config.Configurator.action` method, which allows you to -augment Pyramid's configuration introspection system. +``add_view`` method's callable can assume that, if a ``route_name`` was passed +to it, that a route by this name was already registered by ``add_route``, and +if such a route has not already been registered, it's a configuration error (a +view that names a nonexistent route via its ``route_name`` parameter will never +be called). + +.. versionchanged:: 1.6 + As of Pyramid 1.6 it is possible for one action to invoke another. + +See :ref:`ordering_actions` for more information. + +Finally, ``introspectables`` is a sequence of :term:`introspectable` objects. +You can pass a sequence of introspectables to the +:meth:`~pyramid.config.Configurator.action` method, which allows you to augment +Pyramid's configuration introspection system. .. _ordering_actions: @@ -233,18 +233,17 @@ In Pyramid every :term:`action` has an inherent ordering relative to other actions. The logic within actions is deferred until a call to :meth:`pyramid.config.Configurator.commit` (which is automatically invoked by :meth:`pyramid.config.Configurator.make_wsgi_app`). This means you may call -``config.add_view(route_name='foo')`` **before** -``config.add_route('foo', '/foo')`` because nothing actually happens until -commit-time. During a commit cycle conflicts are resolved, actions are ordered -and executed. +``config.add_view(route_name='foo')`` **before** ``config.add_route('foo', +'/foo')`` because nothing actually happens until commit-time. During a commit +cycle, conflicts are resolved, and actions are ordered and executed. By default, almost every action in Pyramid has an ``order`` of :const:`pyramid.config.PHASE3_CONFIG`. Every action within the same order-level -will be executed in the order it was called. -This means that if an action must be reliably executed before or after another -action, the ``order`` must be defined explicitly to make this work. For -example, views are dependent on routes being defined. Thus the action created -by :meth:`pyramid.config.Configurator.add_route` has an ``order`` of +will be executed in the order it was called. This means that if an action must +be reliably executed before or after another action, the ``order`` must be +defined explicitly to make this work. For example, views are dependent on +routes being defined. Thus the action created by +:meth:`pyramid.config.Configurator.add_route` has an ``order`` of :const:`pyramid.config.PHASE2_CONFIG`. Pre-defined Phases @@ -252,8 +251,8 @@ Pre-defined Phases :const:`pyramid.config.PHASE0_CONFIG` -- This phase is reserved for developers who want to execute actions prior - to Pyramid's core directives. +- This phase is reserved for developers who want to execute actions prior to + Pyramid's core directives. :const:`pyramid.config.PHASE1_CONFIG` @@ -274,17 +273,17 @@ Pre-defined Phases - The default for all builtin or custom directives unless otherwise specified. -Calling Actions From Actions +Calling Actions from Actions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. versionadded:: 1.6 -Pyramid's configurator allows actions to be added during a commit-cycle as -long as they are added to the current or a later ``order`` phase. This means -that your custom action can defer decisions until commit-time and then do -things like invoke :meth:`pyramid.config.Configurator.add_route`. It can also -provide better conflict detection if your addon needs to call more than one -other action. +Pyramid's configurator allows actions to be added during a commit-cycle as long +as they are added to the current or a later ``order`` phase. This means that +your custom action can defer decisions until commit-time and then do things +like invoke :meth:`pyramid.config.Configurator.add_route`. It can also provide +better conflict detection if your addon needs to call more than one other +action. For example, let's make an addon that invokes ``add_route`` and ``add_view``, but we want it to conflict with any other call to our addon: @@ -304,12 +303,12 @@ but we want it to conflict with any other call to our addon: config.action(('auto route', name), register, order=PHASE0_CONFIG) Now someone else can use your addon and be informed if there is a conflict -between this route and another, or two calls to ``add_auto_route``. -Notice how we had to invoke our action **before** ``add_view`` or -``add_route``. If we tried to invoke this afterward, the subsequent calls to -``add_view`` and ``add_route`` would cause conflicts because that phase had -already been executed, and the configurator cannot go back in time to add more -views during that commit-cycle. +between this route and another, or two calls to ``add_auto_route``. Notice how +we had to invoke our action **before** ``add_view`` or ``add_route``. If we +tried to invoke this afterward, the subsequent calls to ``add_view`` and +``add_route`` would cause conflicts because that phase had already been +executed, and the configurator cannot go back in time to add more views during +that commit-cycle. .. code-block:: python :linenos: @@ -341,16 +340,16 @@ All built-in Pyramid directives (such as introspectables when called. For example, when you register a view via ``add_view``, the directive registers at least one introspectable: an introspectable about the view registration itself, providing human-consumable -values for the arguments it was passed. You can later use the introspection -query system to determine whether a particular view uses a renderer, or -whether a particular view is limited to a particular request method, or which -routes a particular view is registered against. The Pyramid "debug toolbar" -makes use of the introspection system in various ways to display information -to Pyramid developers. +values for the arguments passed into it. You can later use the introspection +query system to determine whether a particular view uses a renderer, or whether +a particular view is limited to a particular request method, or against which +routes a particular view is registered. The Pyramid "debug toolbar" makes use +of the introspection system in various ways to display information to Pyramid +developers. -Introspection values are set when a sequence of :term:`introspectable` -objects is passed to the :meth:`~pyramid.config.Configurator.action` method. -Here's an example of a directive which uses introspectables: +Introspection values are set when a sequence of :term:`introspectable` objects +is passed to the :meth:`~pyramid.config.Configurator.action` method. Here's an +example of a directive which uses introspectables: .. code-block:: python :linenos: @@ -370,9 +369,9 @@ Here's an example of a directive which uses introspectables: config.add_directive('add_jammyjam', add_jammyjam) If you notice, the above directive uses the ``introspectable`` attribute of a -Configurator (:attr:`pyramid.config.Configurator.introspectable`) to create -an introspectable object. The introspectable object's constructor requires -at least four arguments: the ``category_name``, the ``discriminator``, the +Configurator (:attr:`pyramid.config.Configurator.introspectable`) to create an +introspectable object. The introspectable object's constructor requires at +least four arguments: the ``category_name``, the ``discriminator``, the ``title``, and the ``type_name``. The ``category_name`` is a string representing the logical category for this @@ -392,19 +391,19 @@ The ``type_name`` is a value that can be used to subtype this introspectable within its category for sorting and presentation purposes. It can be any value. -An introspectable is also dictionary-like. It can contain any set of -key/value pairs, typically related to the arguments passed to its related -directive. While the category_name, discriminator, title and type_name are -*metadata* about the introspectable, the values provided as key/value pairs +An introspectable is also dictionary-like. It can contain any set of key/value +pairs, typically related to the arguments passed to its related directive. +While the ``category_name``, ``discriminator``, ``title``, and ``type_name`` +are *metadata* about the introspectable, the values provided as key/value pairs are the actual data provided by the introspectable. In the above example, we set the ``value`` key to the value of the ``value`` argument passed to the directive. Our directive above mutates the introspectable, and passes it in to the ``action`` method as the first element of a tuple as the value of the -``introspectable`` keyword argument. This associates this introspectable -with the action. Introspection tools will then display this introspectable -in their index. +``introspectable`` keyword argument. This associates this introspectable with +the action. Introspection tools will then display this introspectable in their +index. Introspectable Relationships ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -435,30 +434,29 @@ Two introspectables may have relationships between each other. config.add_directive('add_jammyjam', add_jammyjam) In the above example, the ``add_jammyjam`` directive registers two -introspectables. The first is related to the ``value`` passed to the -directive; the second is related to the ``template`` passed to the directive. -If you believe a concept within a directive is important enough to have its -own introspectable, you can cause the same directive to register more than -one introspectable, registering one introspectable for the "main idea" and -another for a related concept. +introspectables: the first is related to the ``value`` passed to the directive, +and the second is related to the ``template`` passed to the directive. If you +believe a concept within a directive is important enough to have its own +introspectable, you can cause the same directive to register more than one +introspectable, registering one introspectable for the "main idea" and another +for a related concept. The call to ``intr.relate`` above -(:meth:`pyramid.interfaces.IIntrospectable.relate`) is passed two arguments: -a category name and a directive. The example above effectively indicates -that the directive wishes to form a relationship between the ``intr`` -introspectable and the ``tmpl_intr`` introspectable; the arguments passed to -``relate`` are the category name and discriminator of the ``tmpl_intr`` -introspectable. - -Relationships need not be made between two introspectables created by the -same directive. Instead, a relationship can be formed between an -introspectable created in one directive and another introspectable created in -another by calling ``relate`` on either side with the other directive's -category name and discriminator. An error will be raised at configuration -commit time if you attempt to relate an introspectable with another -nonexistent introspectable, however. +(:meth:`pyramid.interfaces.IIntrospectable.relate`) is passed two arguments: a +category name and a directive. The example above effectively indicates that +the directive wishes to form a relationship between the ``intr`` introspectable +and the ``tmpl_intr`` introspectable; the arguments passed to ``relate`` are +the category name and discriminator of the ``tmpl_intr`` introspectable. + +Relationships need not be made between two introspectables created by the same +directive. Instead a relationship can be formed between an introspectable +created in one directive and another introspectable created in another by +calling ``relate`` on either side with the other directive's category name and +discriminator. An error will be raised at configuration commit time if you +attempt to relate an introspectable with another nonexistent introspectable, +however. Introspectable relationships will show up in frontend system renderings of -introspection values. For example, if a view registration names a route -name, the introspectable related to the view callable will show a reference -to the route to which it relates to and vice versa. +introspection values. For example, if a view registration names a route name, +the introspectable related to the view callable will show a reference to the +route to which it relates and vice versa. -- cgit v1.2.3 From 4434b479bcee4d32b8dacaf409bdd756dd7ff8e5 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 6 Nov 2015 01:12:46 -0800 Subject: minor grammar, fix .rst markup, insert versionchanged directive, rewrap to 79 columns --- docs/narr/extconfig.rst | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/docs/narr/extconfig.rst b/docs/narr/extconfig.rst index 5a46c8b9e..fee8d0d3a 100644 --- a/docs/narr/extconfig.rst +++ b/docs/narr/extconfig.rst @@ -215,9 +215,8 @@ view that names a nonexistent route via its ``route_name`` parameter will never be called). .. versionchanged:: 1.6 - As of Pyramid 1.6 it is possible for one action to invoke another. - -See :ref:`ordering_actions` for more information. + As of Pyramid 1.6 it is possible for one action to invoke another. See + :ref:`ordering_actions` for more information. Finally, ``introspectables`` is a sequence of :term:`introspectable` objects. You can pass a sequence of introspectables to the -- cgit v1.2.3 From 28bfdfcb493c577fb445f999d71ca77a096040c3 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 7 Nov 2015 00:39:06 -0800 Subject: minor grammar, fix .rst markup, rewrap to 79 columns --- docs/index.rst | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/index.rst b/docs/index.rst index 70e0948f9..e792b9905 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -82,11 +82,15 @@ join the `#pyramid IRC channel `_. Browse and check out tagged and trunk versions of :app:`Pyramid` via the `Pyramid GitHub repository `_. To check out -the trunk via ``git``, use this command: +the trunk via ``git``, use either command: .. code-block:: text + # If you have SSH keys configured on GitHub: git clone git@github.com:Pylons/pyramid.git + + # Otherwise, HTTPS will work, using your GitHub login: + git clone https://github.com/Pylons/pyramid.git To find out how to become a contributor to :app:`Pyramid`, please see the `contributor's section of the documentation -- cgit v1.2.3 From 31e9347d35ccdee5502672b4e301f51d864508a4 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 9 Nov 2015 02:36:33 -0800 Subject: minor grammar, fix .rst markup, rewrap to 79 columns --- docs/narr/scaffolding.rst | 100 +++++++++++++++++++++++----------------------- 1 file changed, 50 insertions(+), 50 deletions(-) (limited to 'docs') diff --git a/docs/narr/scaffolding.rst b/docs/narr/scaffolding.rst index 4fcdeb537..8677359de 100644 --- a/docs/narr/scaffolding.rst +++ b/docs/narr/scaffolding.rst @@ -4,8 +4,8 @@ Creating Pyramid Scaffolds ========================== You can extend Pyramid by creating a :term:`scaffold` template. A scaffold -template is useful if you'd like to distribute a customizable configuration -of Pyramid to other users. Once you've created a scaffold, and someone has +template is useful if you'd like to distribute a customizable configuration of +Pyramid to other users. Once you've created a scaffold, and someone has installed the distribution that houses the scaffold, they can use the ``pcreate`` script to create a custom version of your scaffold's template. Pyramid itself uses scaffolds to allow people to bootstrap new projects. For @@ -15,22 +15,22 @@ example, ``pcreate -s alchemy MyStuff`` causes Pyramid to render the Basics ------ -A scaffold template is just a bunch of source files and directories on disk. -A small definition class points at this directory; it is in turn pointed at -by a :term:`setuptools` "entry point" which registers the scaffold so it can -be found by the ``pcreate`` command. +A scaffold template is just a bunch of source files and directories on disk. A +small definition class points at this directory. It is in turn pointed at by a +:term:`setuptools` "entry point" which registers the scaffold so it can be +found by the ``pcreate`` command. To create a scaffold template, create a Python :term:`distribution` to house the scaffold which includes a ``setup.py`` that relies on the ``setuptools`` package. See `Creating a Package -`_ for more information -about how to do this. For the sake of example, we'll pretend the -distribution you create is named ``CoolExtension``, and it has a package -directory within it named ``coolextension`` +`_ for more information about +how to do this. For example, we'll pretend the distribution you create is +named ``CoolExtension``, and it has a package directory within it named +``coolextension``. -Once you've created the distribution put a "scaffolds" directory within your -distribution's package directory, and create a file within that directory -named ``__init__.py`` with something like the following: +Once you've created the distribution, put a "scaffolds" directory within your +distribution's package directory, and create a file within that directory named +``__init__.py`` with something like the following: .. code-block:: python :linenos: @@ -54,12 +54,12 @@ As you create files and directories within the template directory, note that: the string value of the variable named ``var`` provided to the scaffold. - Files and directories with filenames that contain the string ``+var+`` will - have that string replaced with the value of the ``var`` variable provided - to the scaffold. + have that string replaced with the value of the ``var`` variable provided to + the scaffold. - Files that start with a dot (e.g., ``.env``) are ignored and will not be copied over to the destination directory. If you want to include a file with - a leading dot then you must replace the dot with ``+dot+`` (e.g., + a leading dot, then you must replace the dot with ``+dot+`` (e.g., ``+dot+env``). Otherwise, files and directories which live in the template directory will be @@ -67,14 +67,14 @@ copied directly without modification to the ``pcreate`` output location. The variables provided by the default ``PyramidTemplate`` include ``project`` (the project name provided by the user as an argument to ``pcreate``), -``package`` (a lowercasing and normalizing of the project name provided by -the user), ``random_string`` (a long random string), and ``package_logger`` -(the name of the package's logger). +``package`` (a lowercasing and normalizing of the project name provided by the +user), ``random_string`` (a long random string), and ``package_logger`` (the +name of the package's logger). See Pyramid's "scaffolds" package -(https://github.com/Pylons/pyramid/tree/master/pyramid/scaffolds) for -concrete examples of scaffold directories (``zodb``, ``alchemy``, and -``starter``, for example). +(https://github.com/Pylons/pyramid/tree/master/pyramid/scaffolds) for concrete +examples of scaffold directories (``zodb``, ``alchemy``, and ``starter``, for +example). After you've created the template directory, add the following to the ``entry_points`` value of your distribution's ``setup.py``: @@ -96,17 +96,16 @@ For example: """ ) -Run your distribution's ``setup.py develop`` or ``setup.py install`` -command. After that, you should be able to see your scaffolding template -listed when you run ``pcreate -l``. It will be named ``coolextension`` -because that's the name we gave it in the entry point setup. Running -``pcreate -s coolextension MyStuff`` will then render your scaffold to an -output directory named ``MyStuff``. +Run your distribution's ``setup.py develop`` or ``setup.py install`` command. +After that, you should be able to see your scaffolding template listed when you +run ``pcreate -l``. It will be named ``coolextension`` because that's the name +we gave it in the entry point setup. Running ``pcreate -s coolextension +MyStuff`` will then render your scaffold to an output directory named +``MyStuff``. -See the module documentation for :mod:`pyramid.scaffolds` for information -about the API of the :class:`pyramid.scaffolds.Template` class and -related classes. You can override methods of this class to get special -behavior. +See the module documentation for :mod:`pyramid.scaffolds` for information about +the API of the :class:`pyramid.scaffolds.Template` class and related classes. +You can override methods of this class to get special behavior. Supporting Older Pyramid Versions --------------------------------- @@ -139,21 +138,22 @@ defining your scaffold template: And then in the setup.py of the package that contains your scaffold, define the template as a target of both ``paste.paster_create_template`` (for -``paster create``) and ``pyramid.scaffold`` (for ``pcreate``):: +``paster create``) and ``pyramid.scaffold`` (for ``pcreate``). - [paste.paster_create_template] - coolextension=coolextension.scaffolds:CoolExtensionTemplate - [pyramid.scaffold] - coolextension=coolextension.scaffolds:CoolExtensionTemplate +.. code-block:: ini + + [paste.paster_create_template] + coolextension=coolextension.scaffolds:CoolExtensionTemplate + [pyramid.scaffold] + coolextension=coolextension.scaffolds:CoolExtensionTemplate -Doing this hideousness will allow your scaffold to work as a ``paster -create`` target (under 1.0, 1.1, or 1.2) or as a ``pcreate`` target (under -1.3). If an invoker tries to run ``paster create`` against a scaffold -defined this way under 1.3, an error is raised instructing them to use -``pcreate`` instead. +Doing this hideousness will allow your scaffold to work as a ``paster create`` +target (under 1.0, 1.1, or 1.2) or as a ``pcreate`` target (under 1.3). If an +invoker tries to run ``paster create`` against a scaffold defined this way +under 1.3, an error is raised instructing them to use ``pcreate`` instead. -If you want only to support Pyramid 1.3 only, it's much cleaner, and the API -is stable: +If you want to support Pyramid 1.3 only, it's much cleaner, and the API is +stable: .. code-block:: python :linenos: @@ -164,17 +164,17 @@ is stable: _template_dir = 'coolextension_scaffold' summary = 'My cool_extension' -You only need to specify a ``paste.paster_create_template`` entry point -target in your ``setup.py`` if you want your scaffold to be consumable by -users of Pyramid 1.0, 1.1, or 1.2. To support only 1.3, specifying only the +You only need to specify a ``paste.paster_create_template`` entry point target +in your ``setup.py`` if you want your scaffold to be consumable by users of +Pyramid 1.0, 1.1, or 1.2. To support only 1.3, specifying only the ``pyramid.scaffold`` entry point is good enough. If you want to support both -``paster create`` and ``pcreate`` (meaning you want to support Pyramid 1.2 -and some older version), you'll need to define both. +``paster create`` and ``pcreate`` (meaning you want to support Pyramid 1.2 and +some older version), you'll need to define both. Examples -------- Existing third-party distributions which house scaffolding are available via -:term:`PyPI`. The ``pyramid_jqm``, ``pyramid_zcml`` and ``pyramid_jinja2`` +:term:`PyPI`. The ``pyramid_jqm``, ``pyramid_zcml``, and ``pyramid_jinja2`` packages house scaffolds. You can install and examine these packages to see how they work in the quest to develop your own scaffolding. -- cgit v1.2.3 From bb38205e27165f1af19600a64eef702372cbb7a7 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 10 Nov 2015 01:03:05 -0800 Subject: - remove sqla_demo.sqlite db: it's generated by the user --- docs/quick_tour/sqla_demo/sqla_demo.sqlite | Bin 3072 -> 0 bytes 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo.sqlite (limited to 'docs') diff --git a/docs/quick_tour/sqla_demo/sqla_demo.sqlite b/docs/quick_tour/sqla_demo/sqla_demo.sqlite deleted file mode 100644 index fa6adb104..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo.sqlite and /dev/null differ -- cgit v1.2.3 From c4c37a63c48bb86712da61984fc56258b9a64ff1 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 10 Nov 2015 03:05:33 -0800 Subject: - update files at project root --- docs/quick_tour/sqla_demo/development.ini | 4 ++-- docs/quick_tour/sqla_demo/production.ini | 2 +- docs/quick_tour/sqla_demo/setup.py | 11 +++++++---- 3 files changed, 10 insertions(+), 7 deletions(-) (limited to 'docs') diff --git a/docs/quick_tour/sqla_demo/development.ini b/docs/quick_tour/sqla_demo/development.ini index 174468abf..0db0950a0 100644 --- a/docs/quick_tour/sqla_demo/development.ini +++ b/docs/quick_tour/sqla_demo/development.ini @@ -27,7 +27,7 @@ sqlalchemy.url = sqlite:///%(here)s/sqla_demo.sqlite [server:main] use = egg:waitress#main -host = 0.0.0.0 +host = 127.0.0.1 port = 6543 ### @@ -68,4 +68,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/sqla_demo/production.ini b/docs/quick_tour/sqla_demo/production.ini index dc0ba304f..38f3b6318 100644 --- a/docs/quick_tour/sqla_demo/production.ini +++ b/docs/quick_tour/sqla_demo/production.ini @@ -59,4 +59,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/sqla_demo/setup.py b/docs/quick_tour/sqla_demo/setup.py index ac2eed035..312a97c06 100644 --- a/docs/quick_tour/sqla_demo/setup.py +++ b/docs/quick_tour/sqla_demo/setup.py @@ -3,15 +3,18 @@ import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) -README = open(os.path.join(here, 'README.txt')).read() -CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() +with open(os.path.join(here, 'README.txt')) as f: + README = f.read() +with open(os.path.join(here, 'CHANGES.txt')) as f: + CHANGES = f.read() requires = [ 'pyramid', + 'pyramid_jinja2', + 'pyramid_debugtoolbar', + 'pyramid_tm', 'SQLAlchemy', 'transaction', - 'pyramid_tm', - 'pyramid_debugtoolbar', 'zope.sqlalchemy', 'waitress', ] -- cgit v1.2.3 From 11c1c0241666c6be3b2af5330a1edd2c1ce8194a Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 10 Nov 2015 03:10:45 -0800 Subject: sqla_demo/sqla_demo/ - update __init__.py and tests.py - remove models.py and views.py in preference to modules --- docs/quick_tour/sqla_demo/sqla_demo/__init__.py | 11 +--- docs/quick_tour/sqla_demo/sqla_demo/models.py | 29 ----------- docs/quick_tour/sqla_demo/sqla_demo/tests.py | 68 ++++++++++++++++++------- docs/quick_tour/sqla_demo/sqla_demo/views.py | 37 -------------- 4 files changed, 52 insertions(+), 93 deletions(-) delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models.py delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/views.py (limited to 'docs') diff --git a/docs/quick_tour/sqla_demo/sqla_demo/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/__init__.py index aac7c5e69..7994bbfa8 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/__init__.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/__init__.py @@ -1,19 +1,12 @@ from pyramid.config import Configurator -from sqlalchemy import engine_from_config - -from .models import ( - DBSession, - Base, - ) def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ - engine = engine_from_config(settings, 'sqlalchemy.') - DBSession.configure(bind=engine) - Base.metadata.bind = engine config = Configurator(settings=settings) + config.include('pyramid_jinja2') + config.include('.models.meta') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models.py b/docs/quick_tour/sqla_demo/sqla_demo/models.py deleted file mode 100644 index 3dfb40e58..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/models.py +++ /dev/null @@ -1,29 +0,0 @@ -from sqlalchemy import ( - Column, - Integer, - Text, - ) - -from sqlalchemy.ext.declarative import declarative_base - -from sqlalchemy.orm import ( - scoped_session, - sessionmaker, - ) - -from zope.sqlalchemy import ZopeTransactionExtension - -DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) -Base = declarative_base() - -# Start Sphinx Include -class MyModel(Base): - __tablename__ = 'models' - id = Column(Integer, primary_key=True) - name = Column(Text, unique=True) - value = Column(Integer) - - def __init__(self, name, value): - self.name = name - self.value = value - # End Sphinx Include diff --git a/docs/quick_tour/sqla_demo/sqla_demo/tests.py b/docs/quick_tour/sqla_demo/sqla_demo/tests.py index 6fef6d695..b6b6fdf4d 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/tests.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/tests.py @@ -3,31 +3,63 @@ import transaction from pyramid import testing -from .models import DBSession +def dummy_request(dbsession): + return testing.DummyRequest(dbsession=dbsession) -class TestMyView(unittest.TestCase): + +class BaseTest(unittest.TestCase): def setUp(self): - self.config = testing.setUp() - from sqlalchemy import create_engine - engine = create_engine('sqlite://') - from .models import ( - Base, - MyModel, + self.config = testing.setUp(settings={ + 'sqlalchemy.url': 'sqlite:///:memory:' + }) + self.config.include('.models.meta') + settings = self.config.get_settings() + + from .models.meta import ( + get_session, + get_engine, + get_dbmaker, ) - DBSession.configure(bind=engine) - Base.metadata.create_all(engine) - with transaction.manager: - model = MyModel(name='one', value=55) - DBSession.add(model) + + self.engine = get_engine(settings) + dbmaker = get_dbmaker(self.engine) + + self.session = get_session(transaction.manager, dbmaker) + + def init_database(self): + from .models.meta import Base + Base.metadata.create_all(self.engine) def tearDown(self): - DBSession.remove() + from .models.meta import Base + testing.tearDown() + transaction.abort() + Base.metadata.create_all(self.engine) + + +class TestMyViewSuccessCondition(BaseTest): - def test_it(self): - from .views import my_view - request = testing.DummyRequest() - info = my_view(request) + def setUp(self): + super(TestMyViewSuccessCondition, self).setUp() + self.init_database() + + from .models.mymodel import MyModel + + model = MyModel(name='one', value=55) + self.session.add(model) + + def test_passing_view(self): + from .views.default import my_view + info = my_view(dummy_request(self.session)) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'sqla_demo') + + +class TestMyViewFailureCondition(BaseTest): + + def test_failing_view(self): + from .views.default import my_view + info = my_view(dummy_request(self.session)) + self.assertEqual(info.status_int, 500) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views.py b/docs/quick_tour/sqla_demo/sqla_demo/views.py deleted file mode 100644 index 768a7e42e..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/views.py +++ /dev/null @@ -1,37 +0,0 @@ -from pyramid.response import Response -from pyramid.view import view_config - -from sqlalchemy.exc import DBAPIError - -from .models import ( - DBSession, - MyModel, - ) - - -@view_config(route_name='home', renderer='templates/mytemplate.pt') -def my_view(request): - try: - # Start Sphinx Include - one = DBSession.query(MyModel).filter(MyModel.name == 'one').first() - # End Sphinx Include - except DBAPIError: - return Response(conn_err_msg, content_type='text/plain', status_int=500) - return {'one': one, 'project': 'sqla_demo'} - -conn_err_msg = """\ -Pyramid is having a problem using your SQL database. The problem -might be caused by one of the following things: - -1. You may need to run the "initialize_sqla_demo_db" script - to initialize your database tables. Check your virtual - environment's "bin" directory for this script and try to run it. - -2. Your database server may not be running. Check that the - database server referred to by the "sqlalchemy.url" setting in - your "development.ini" file is running. - -After you fix the problem, please restart the Pyramid application to -try it again. -""" - -- cgit v1.2.3 From 38a82f07a9ae8cf30d128479794f6c3e3875da28 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 10 Nov 2015 03:12:47 -0800 Subject: sqla_demo/sqla_demo - update /scripts, /static, and /templates --- .../sqla_demo/sqla_demo/scripts/initializedb.py | 30 +- .../sqla_demo/sqla_demo/static/favicon.ico | Bin 1406 -> 0 bytes .../sqla_demo/sqla_demo/static/footerbg.png | Bin 333 -> 0 bytes .../sqla_demo/sqla_demo/static/headerbg.png | Bin 203 -> 0 bytes docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css | 8 - .../sqla_demo/sqla_demo/static/middlebg.png | Bin 2797 -> 0 bytes .../sqla_demo/sqla_demo/static/pylons.css | 372 --------------------- .../sqla_demo/sqla_demo/static/pyramid-small.png | Bin 7044 -> 0 bytes .../sqla_demo/sqla_demo/static/pyramid.png | Bin 33055 -> 12901 bytes .../sqla_demo/sqla_demo/static/transparent.gif | Bin 49 -> 0 bytes .../sqla_demo/sqla_demo/templates/mytemplate.pt | 76 ----- 11 files changed, 19 insertions(+), 467 deletions(-) delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt (limited to 'docs') diff --git a/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py b/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py index 66feb3008..f0d09729e 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py @@ -2,36 +2,44 @@ import os import sys import transaction -from sqlalchemy import engine_from_config - from pyramid.paster import ( get_appsettings, setup_logging, ) -from ..models import ( - DBSession, - MyModel, +from pyramid.scripts.common import parse_vars + +from ..models.meta import ( Base, + get_session, + get_engine, + get_dbmaker, ) +from ..models.mymodel import MyModel def usage(argv): cmd = os.path.basename(argv[0]) - print('usage: %s \n' + print('usage: %s [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): - if len(argv) != 2: + if len(argv) < 2: usage(argv) config_uri = argv[1] + options = parse_vars(argv[2:]) setup_logging(config_uri) - settings = get_appsettings(config_uri) - engine = engine_from_config(settings, 'sqlalchemy.') - DBSession.configure(bind=engine) + settings = get_appsettings(config_uri, options=options) + + engine = get_engine(settings) + dbmaker = get_dbmaker(engine) + + dbsession = get_session(transaction.manager, dbmaker) + Base.metadata.create_all(engine) + with transaction.manager: model = MyModel(name='one', value=1) - DBSession.add(model) + dbsession.add(model) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico b/docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico deleted file mode 100644 index 71f837c9e..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png b/docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png deleted file mode 100644 index 1fbc873da..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png b/docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png deleted file mode 100644 index 0596f2020..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css b/docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css deleted file mode 100644 index b7c8493d8..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css +++ /dev/null @@ -1,8 +0,0 @@ -* html img, -* html .png{position:relative;behavior:expression((this.runtimeStyle.behavior="none")&&(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none", -this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "',sizingMethod='image')", -this.src = "static/transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''), -this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "',sizingMethod='crop')", -this.runtimeStyle.backgroundImage = "none")),this.pngSet=true) -);} -#wrap{display:table;height:100%} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png b/docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png deleted file mode 100644 index 2369cfb7d..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css b/docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css deleted file mode 100644 index 4b1c017cd..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css +++ /dev/null @@ -1,372 +0,0 @@ -html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td -{ - margin: 0; - padding: 0; - border: 0; - outline: 0; - font-size: 100%; /* 16px */ - vertical-align: baseline; - background: transparent; -} - -body -{ - line-height: 1; -} - -ol, ul -{ - list-style: none; -} - -blockquote, q -{ - quotes: none; -} - -blockquote:before, blockquote:after, q:before, q:after -{ - content: ''; - content: none; -} - -:focus -{ - outline: 0; -} - -ins -{ - text-decoration: none; -} - -del -{ - text-decoration: line-through; -} - -table -{ - border-collapse: collapse; - border-spacing: 0; -} - -sub -{ - vertical-align: sub; - font-size: smaller; - line-height: normal; -} - -sup -{ - vertical-align: super; - font-size: smaller; - line-height: normal; -} - -ul, menu, dir -{ - display: block; - list-style-type: disc; - margin: 1em 0; - padding-left: 40px; -} - -ol -{ - display: block; - list-style-type: decimal-leading-zero; - margin: 1em 0; - padding-left: 40px; -} - -li -{ - display: list-item; -} - -ul ul, ul ol, ul dir, ul menu, ul dl, ol ul, ol ol, ol dir, ol menu, ol dl, dir ul, dir ol, dir dir, dir menu, dir dl, menu ul, menu ol, menu dir, menu menu, menu dl, dl ul, dl ol, dl dir, dl menu, dl dl -{ - margin-top: 0; - margin-bottom: 0; -} - -ol ul, ul ul, menu ul, dir ul, ol menu, ul menu, menu menu, dir menu, ol dir, ul dir, menu dir, dir dir -{ - list-style-type: circle; -} - -ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ol dir, ol ul dir, ol menu dir, ol dir dir, ul ol ul, ul ul ul, ul menu ul, ul dir ul, ul ol menu, ul ul menu, ul menu menu, ul dir menu, ul ol dir, ul ul dir, ul menu dir, ul dir dir, menu ol ul, menu ul ul, menu menu ul, menu dir ul, menu ol menu, menu ul menu, menu menu menu, menu dir menu, menu ol dir, menu ul dir, menu menu dir, menu dir dir, dir ol ul, dir ul ul, dir menu ul, dir dir ul, dir ol menu, dir ul menu, dir menu menu, dir dir menu, dir ol dir, dir ul dir, dir menu dir, dir dir dir -{ - list-style-type: square; -} - -.hidden -{ - display: none; -} - -p -{ - line-height: 1.5em; -} - -h1 -{ - font-size: 1.75em; - line-height: 1.7em; - font-family: helvetica, verdana; -} - -h2 -{ - font-size: 1.5em; - line-height: 1.7em; - font-family: helvetica, verdana; -} - -h3 -{ - font-size: 1.25em; - line-height: 1.7em; - font-family: helvetica, verdana; -} - -h4 -{ - font-size: 1em; - line-height: 1.7em; - font-family: helvetica, verdana; -} - -html, body -{ - width: 100%; - height: 100%; -} - -body -{ - margin: 0; - padding: 0; - background-color: #fff; - position: relative; - font: 16px/24px NobileRegular, "Lucida Grande", Lucida, Verdana, sans-serif; -} - -a -{ - color: #1b61d6; - text-decoration: none; -} - -a:hover -{ - color: #e88f00; - text-decoration: underline; -} - -body h1, body h2, body h3, body h4, body h5, body h6 -{ - font-family: NeutonRegular, "Lucida Grande", Lucida, Verdana, sans-serif; - font-weight: 400; - color: #373839; - font-style: normal; -} - -#wrap -{ - min-height: 100%; -} - -#header, #footer -{ - width: 100%; - color: #fff; - height: 40px; - position: absolute; - text-align: center; - line-height: 40px; - overflow: hidden; - font-size: 12px; - vertical-align: middle; -} - -#header -{ - background: #000; - top: 0; - font-size: 14px; -} - -#footer -{ - bottom: 0; - background: #000 url(footerbg.png) repeat-x 0 top; - position: relative; - margin-top: -40px; - clear: both; -} - -.header, .footer -{ - width: 750px; - margin-right: auto; - margin-left: auto; -} - -.wrapper -{ - width: 100%; -} - -#top, #top-small, #bottom -{ - width: 100%; -} - -#top -{ - color: #000; - height: 230px; - background: #fff url(headerbg.png) repeat-x 0 top; - position: relative; -} - -#top-small -{ - color: #000; - height: 60px; - background: #fff url(headerbg.png) repeat-x 0 top; - position: relative; -} - -#bottom -{ - color: #222; - background-color: #fff; -} - -.top, .top-small, .middle, .bottom -{ - width: 750px; - margin-right: auto; - margin-left: auto; -} - -.top -{ - padding-top: 40px; -} - -.top-small -{ - padding-top: 10px; -} - -#middle -{ - width: 100%; - height: 100px; - background: url(middlebg.png) repeat-x; - border-top: 2px solid #fff; - border-bottom: 2px solid #b2b2b2; -} - -.app-welcome -{ - margin-top: 25px; -} - -.app-name -{ - color: #000; - font-weight: 700; -} - -.bottom -{ - padding-top: 50px; -} - -#left -{ - width: 350px; - float: left; - padding-right: 25px; -} - -#right -{ - width: 350px; - float: right; - padding-left: 25px; -} - -.align-left -{ - text-align: left; -} - -.align-right -{ - text-align: right; -} - -.align-center -{ - text-align: center; -} - -ul.links -{ - margin: 0; - padding: 0; -} - -ul.links li -{ - list-style-type: none; - font-size: 14px; -} - -form -{ - border-style: none; -} - -fieldset -{ - border-style: none; -} - -input -{ - color: #222; - border: 1px solid #ccc; - font-family: sans-serif; - font-size: 12px; - line-height: 16px; -} - -input[type=text], input[type=password] -{ - width: 205px; -} - -input[type=submit] -{ - background-color: #ddd; - font-weight: 700; -} - -/*Opera Fix*/ -body:before -{ - content: ""; - height: 100%; - float: left; - width: 0; - margin-top: -32767px; -} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png deleted file mode 100644 index a5bc0ade7..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png index 347e05549..4ab837be9 100644 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png and b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif b/docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif deleted file mode 100644 index 0341802e5..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt deleted file mode 100644 index 321c0f5fb..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt +++ /dev/null @@ -1,76 +0,0 @@ - - - - The Pyramid Web Framework - - - - - - - - - - -
-
-
-
pyramid
-
-
-
-
-

- Welcome to ${project}, an application generated by
- the Pyramid web framework. -

-
-
-
-
-
-

Search documentation

-
- - -
-
- -
-
-
- - - -- cgit v1.2.3 From 6e4924f31ca7f68991555938242efe1860ec5908 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 10 Nov 2015 03:14:06 -0800 Subject: sqla_demo/sqla_demo - add /models, /static, /templates, and /views --- .../sqla_demo/sqla_demo/models/__init__.py | 7 + docs/quick_tour/sqla_demo/sqla_demo/models/meta.py | 46 ++++++ .../sqla_demo/sqla_demo/models/mymodel.py | 17 +++ .../sqla_demo/sqla_demo/static/pyramid-16x16.png | Bin 0 -> 1319 bytes .../sqla_demo/sqla_demo/static/theme.css | 154 +++++++++++++++++++++ .../sqla_demo/sqla_demo/static/theme.min.css | 1 + .../sqla_demo/sqla_demo/templates/layout.jinja2 | 66 +++++++++ .../sqla_demo/templates/mytemplate.jinja2 | 8 ++ .../sqla_demo/sqla_demo/views/__init__.py | 0 .../sqla_demo/sqla_demo/views/default.py | 33 +++++ 10 files changed, 332 insertions(+) create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models/meta.py create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/theme.css create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/views/__init__.py create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/views/default.py (limited to 'docs') diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py new file mode 100644 index 000000000..6ffc10a78 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py @@ -0,0 +1,7 @@ +from sqlalchemy.orm import configure_mappers +# import all models classes here for sqlalchemy mappers +# to pick up +from .mymodel import MyModel # flake8: noqa + +# run configure mappers to ensure we avoid any race conditions +configure_mappers() diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/meta.py b/docs/quick_tour/sqla_demo/sqla_demo/models/meta.py new file mode 100644 index 000000000..b72b45f9f --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/models/meta.py @@ -0,0 +1,46 @@ +from sqlalchemy import engine_from_config +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +from sqlalchemy.schema import MetaData +import zope.sqlalchemy + +NAMING_CONVENTION = { + "ix": 'ix_%(column_0_label)s', + "uq": "uq_%(table_name)s_%(column_0_name)s", + "ck": "ck_%(table_name)s_%(constraint_name)s", + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", + "pk": "pk_%(table_name)s" +} + +metadata = MetaData(naming_convention=NAMING_CONVENTION) +Base = declarative_base(metadata=metadata) + + +def includeme(config): + settings = config.get_settings() + dbmaker = get_dbmaker(get_engine(settings)) + + config.add_request_method( + lambda r: get_session(r.tm, dbmaker), + 'dbsession', + reify=True + ) + + config.include('pyramid_tm') + + +def get_session(transaction_manager, dbmaker): + dbsession = dbmaker() + zope.sqlalchemy.register(dbsession, + transaction_manager=transaction_manager) + return dbsession + + +def get_engine(settings, prefix='sqlalchemy.'): + return engine_from_config(settings, prefix) + + +def get_dbmaker(engine): + dbmaker = sessionmaker() + dbmaker.configure(bind=engine) + return dbmaker diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py b/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py new file mode 100644 index 000000000..5a2b5890c --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py @@ -0,0 +1,17 @@ +from .meta import Base +from sqlalchemy import ( + Column, + Index, + Integer, + Text, +) + + +class MyModel(Base): + __tablename__ = 'models' + id = Column(Integer, primary_key=True) + name = Column(Text) + value = Column(Integer) + + +Index('my_index', MyModel.name, unique=True, mysql_length=255) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png new file mode 100644 index 000000000..979203112 Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css new file mode 100644 index 000000000..0f4b1a4d4 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css @@ -0,0 +1,154 @@ +@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700); +body { + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-weight: 300; + color: #ffffff; + background: #bc2131; +} +h1, +h2, +h3, +h4, +h5, +h6 { + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-weight: 300; +} +p { + font-weight: 300; +} +.font-normal { + font-weight: 400; +} +.font-semi-bold { + font-weight: 600; +} +.font-bold { + font-weight: 700; +} +.starter-template { + margin-top: 250px; +} +.starter-template .content { + margin-left: 10px; +} +.starter-template .content h1 { + margin-top: 10px; + font-size: 60px; +} +.starter-template .content h1 .smaller { + font-size: 40px; + color: #f2b7bd; +} +.starter-template .content .lead { + font-size: 25px; + color: #f2b7bd; +} +.starter-template .content .lead .font-normal { + color: #ffffff; +} +.starter-template .links { + float: right; + right: 0; + margin-top: 125px; +} +.starter-template .links ul { + display: block; + padding: 0; + margin: 0; +} +.starter-template .links ul li { + list-style: none; + display: inline; + margin: 0 10px; +} +.starter-template .links ul li:first-child { + margin-left: 0; +} +.starter-template .links ul li:last-child { + margin-right: 0; +} +.starter-template .links ul li.current-version { + color: #f2b7bd; + font-weight: 400; +} +.starter-template .links ul li a, a { + color: #f2b7bd; + text-decoration: underline; +} +.starter-template .links ul li a:hover, a:hover { + color: #ffffff; + text-decoration: underline; +} +.starter-template .links ul li .icon-muted { + color: #eb8b95; + margin-right: 5px; +} +.starter-template .links ul li:hover .icon-muted { + color: #ffffff; +} +.starter-template .copyright { + margin-top: 10px; + font-size: 0.9em; + color: #f2b7bd; + text-transform: lowercase; + float: right; + right: 0; +} +@media (max-width: 1199px) { + .starter-template .content h1 { + font-size: 45px; + } + .starter-template .content h1 .smaller { + font-size: 30px; + } + .starter-template .content .lead { + font-size: 20px; + } +} +@media (max-width: 991px) { + .starter-template { + margin-top: 0; + } + .starter-template .logo { + margin: 40px auto; + } + .starter-template .content { + margin-left: 0; + text-align: center; + } + .starter-template .content h1 { + margin-bottom: 20px; + } + .starter-template .links { + float: none; + text-align: center; + margin-top: 60px; + } + .starter-template .copyright { + float: none; + text-align: center; + } +} +@media (max-width: 767px) { + .starter-template .content h1 .smaller { + font-size: 25px; + display: block; + } + .starter-template .content .lead { + font-size: 16px; + } + .starter-template .links { + margin-top: 40px; + } + .starter-template .links ul li { + display: block; + margin: 0; + } + .starter-template .links ul li .icon-muted { + display: none; + } + .starter-template .copyright { + margin-top: 20px; + } +} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css new file mode 100644 index 000000000..0d25de5b6 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css @@ -0,0 +1 @@ +@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700);body{font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:300;color:#fff;background:#bc2131}h1,h2,h3,h4,h5,h6{font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:300}p{font-weight:300}.font-normal{font-weight:400}.font-semi-bold{font-weight:600}.font-bold{font-weight:700}.starter-template{margin-top:250px}.starter-template .content{margin-left:10px}.starter-template .content h1{margin-top:10px;font-size:60px}.starter-template .content h1 .smaller{font-size:40px;color:#f2b7bd}.starter-template .content .lead{font-size:25px;color:#f2b7bd}.starter-template .content .lead .font-normal{color:#fff}.starter-template .links{float:right;right:0;margin-top:125px}.starter-template .links ul{display:block;padding:0;margin:0}.starter-template .links ul li{list-style:none;display:inline;margin:0 10px}.starter-template .links ul li:first-child{margin-left:0}.starter-template .links ul li:last-child{margin-right:0}.starter-template .links ul li.current-version{color:#f2b7bd;font-weight:400}.starter-template .links ul li a,a{color:#f2b7bd;text-decoration:underline}.starter-template .links ul li a:hover,a:hover{color:#fff;text-decoration:underline}.starter-template .links ul li .icon-muted{color:#eb8b95;margin-right:5px}.starter-template .links ul li:hover .icon-muted{color:#fff}.starter-template .copyright{margin-top:10px;font-size:.9em;color:#f2b7bd;text-transform:lowercase;float:right;right:0}@media (max-width:1199px){.starter-template .content h1{font-size:45px}.starter-template .content h1 .smaller{font-size:30px}.starter-template .content .lead{font-size:20px}}@media (max-width:991px){.starter-template{margin-top:0}.starter-template .logo{margin:40px auto}.starter-template .content{margin-left:0;text-align:center}.starter-template .content h1{margin-bottom:20px}.starter-template .links{float:none;text-align:center;margin-top:60px}.starter-template .copyright{float:none;text-align:center}}@media (max-width:767px){.starter-template .content h1 .smaller{font-size:25px;display:block}.starter-template .content .lead{font-size:16px}.starter-template .links{margin-top:40px}.starter-template .links ul li{display:block;margin:0}.starter-template .links ul li .icon-muted{display:none}.starter-template .copyright{margin-top:20px}} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 b/docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 new file mode 100644 index 000000000..76a098122 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 @@ -0,0 +1,66 @@ + + + + + + + + + + + Alchemy Scaffold for The Pyramid Web Framework + + + + + + + + + + + + + +
+
+
+
+ +
+
+ {% block content %} +

No content

+ {% endblock content %} +
+
+
+ +
+
+ +
+
+
+ + + + + + + + diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 new file mode 100644 index 000000000..bb622bf5a --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 @@ -0,0 +1,8 @@ +{% extends "layout.jinja2" %} + +{% block content %} +
+

Pyramid Alchemy scaffold

+

Welcome to {{project}}, an application generated by
the Pyramid Web Framework 1.7.dev0.

+
+{% endblock content %} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/views/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views/default.py b/docs/quick_tour/sqla_demo/sqla_demo/views/default.py new file mode 100644 index 000000000..4c659e5c2 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/views/default.py @@ -0,0 +1,33 @@ +from pyramid.response import Response +from pyramid.view import view_config + +from sqlalchemy.exc import DBAPIError + +from ..models.mymodel import MyModel + + +@view_config(route_name='home', renderer='../templates/mytemplate.jinja2') +def my_view(request): + try: + query = request.dbsession.query(MyModel) + one = query.filter(MyModel.name == 'one').first() + except DBAPIError: + return Response(db_err_msg, content_type='text/plain', status_int=500) + return {'one': one, 'project': 'sqla_demo'} + + +db_err_msg = """\ +Pyramid is having a problem using your SQL database. The problem +might be caused by one of the following things: + +1. You may need to run the "initialize_sqla_demo_db" script + to initialize your database tables. Check your virtual + environment's "bin" directory for this script and try to run it. + +2. Your database server may not be running. Check that the + database server referred to by the "sqlalchemy.url" setting in + your "development.ini" file is running. + +After you fix the problem, please restart the Pyramid application to +try it again. +""" -- cgit v1.2.3 From 7d54301859565c789eb12bb8b0b0dd7049704c1c Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 11 Nov 2015 18:18:55 -0800 Subject: sqla_demo/sqla_demo - add /models, /static, /templates, and /views --- docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py | 2 ++ docs/quick_tour/sqla_demo/sqla_demo/views/default.py | 2 ++ 2 files changed, 4 insertions(+) (limited to 'docs') diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py b/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py index 5a2b5890c..eb645bfe6 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py @@ -7,11 +7,13 @@ from sqlalchemy import ( ) +# Start Sphinx Include class MyModel(Base): __tablename__ = 'models' id = Column(Integer, primary_key=True) name = Column(Text) value = Column(Integer) + # End Sphinx Include Index('my_index', MyModel.name, unique=True, mysql_length=255) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views/default.py b/docs/quick_tour/sqla_demo/sqla_demo/views/default.py index 4c659e5c2..e5e70cf9d 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/views/default.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/views/default.py @@ -10,7 +10,9 @@ from ..models.mymodel import MyModel def my_view(request): try: query = request.dbsession.query(MyModel) + # Start Sphinx Include one = query.filter(MyModel.name == 'one').first() + # End Sphinx Include except DBAPIError: return Response(db_err_msg, content_type='text/plain', status_int=500) return {'one': one, 'project': 'sqla_demo'} -- cgit v1.2.3 From 91ccc4540800708e7d312fe4a988edb0a9543624 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 11 Nov 2015 18:23:54 -0800 Subject: sqla_demo/sqla_demo - update references in literalincludes --- docs/quick_tour.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index be5be2e36..87c6f1e1c 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -818,14 +818,14 @@ The ORM eases the mapping of database structures into a programming language. SQLAlchemy uses "models" for this mapping. The scaffold generated a sample model: -.. literalinclude:: quick_tour/sqla_demo/sqla_demo/models.py +.. literalinclude:: quick_tour/sqla_demo/sqla_demo/models/mymodel.py :start-after: Start Sphinx Include :end-before: End Sphinx Include View code, which mediates the logic between web requests and the rest of the system, can then easily get at the data thanks to SQLAlchemy: -.. literalinclude:: quick_tour/sqla_demo/sqla_demo/views.py +.. literalinclude:: quick_tour/sqla_demo/sqla_demo/views/default.py :start-after: Start Sphinx Include :end-before: End Sphinx Include -- cgit v1.2.3 From c043c779861b7a710ef326d912b57ddf1fed8eaa Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 11 Nov 2015 18:27:03 -0800 Subject: wiki2/src/basiclayout/ - update ini files using new scaffold --- docs/tutorials/wiki2/src/basiclayout/development.ini | 4 ++-- docs/tutorials/wiki2/src/basiclayout/production.ini | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/docs/tutorials/wiki2/src/basiclayout/development.ini b/docs/tutorials/wiki2/src/basiclayout/development.ini index a9d53b296..99c4ff0fe 100644 --- a/docs/tutorials/wiki2/src/basiclayout/development.ini +++ b/docs/tutorials/wiki2/src/basiclayout/development.ini @@ -27,7 +27,7 @@ sqlalchemy.url = sqlite:///%(here)s/tutorial.sqlite [server:main] use = egg:waitress#main -host = 0.0.0.0 +host = 127.0.0.1 port = 6543 ### @@ -68,4 +68,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/tutorials/wiki2/src/basiclayout/production.ini b/docs/tutorials/wiki2/src/basiclayout/production.ini index fa94c1b3e..97acfbd7d 100644 --- a/docs/tutorials/wiki2/src/basiclayout/production.ini +++ b/docs/tutorials/wiki2/src/basiclayout/production.ini @@ -59,4 +59,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s -- cgit v1.2.3 From fea87a5cbb4edbfef204283c23d5b0d8fb5220f8 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 11 Nov 2015 18:34:44 -0800 Subject: - update basiclayout/tutorial/__init__.py - update section "Application configuration with ``__init__.py``" - move WIP to "Content Models with ``models.py``", wrapped by Sphinx comments --- docs/tutorials/wiki2/basiclayout.rst | 98 ++++++++++++---------- .../wiki2/src/basiclayout/tutorial/__init__.py | 12 +-- 2 files changed, 57 insertions(+), 53 deletions(-) (limited to 'docs') diff --git a/docs/tutorials/wiki2/basiclayout.rst b/docs/tutorials/wiki2/basiclayout.rst index 80ae4b34e..8a1dbf3f8 100644 --- a/docs/tutorials/wiki2/basiclayout.rst +++ b/docs/tutorials/wiki2/basiclayout.rst @@ -12,12 +12,12 @@ Application configuration with ``__init__.py`` A directory on disk can be turned into a Python :term:`package` by containing an ``__init__.py`` file. Even if empty, this marks a directory as a Python -package. We use ``__init__.py`` both as a marker, indicating the directory -in which it's contained is a package, and to contain application configuration +package. We use ``__init__.py`` both as a marker, indicating the directory in +which it's contained is a package, and to contain application configuration code. -Open ``tutorial/tutorial/__init__.py``. It should already contain -the following: +Open ``tutorial/tutorial/__init__.py``. It should already contain the +following: .. literalinclude:: src/basiclayout/tutorial/__init__.py :linenos: @@ -43,58 +43,37 @@ When you invoke the ``pserve development.ini`` command, the ``main`` function above is executed. It accepts some settings and returns a :term:`WSGI` application. (See :ref:`startup_chapter` for more about ``pserve``.) -The main function first creates a :term:`SQLAlchemy` database engine using -:func:`sqlalchemy.engine_from_config` from the ``sqlalchemy.`` prefixed -settings in the ``development.ini`` file's ``[app:main]`` section. -This will be a URI (something like ``sqlite://``): - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 13 - :language: py - -``main`` then initializes our SQLAlchemy session object, passing it the -engine: - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 14 - :language: py - -``main`` subsequently initializes our SQLAlchemy declarative ``Base`` object, -assigning the engine we created to the ``bind`` attribute of it's -``metadata`` object. This allows table definitions done imperatively -(instead of declaratively, via a class statement) to work. We won't use any -such tables in our application, but if you add one later, long after you've -forgotten about this tutorial, you won't be left scratching your head when it -doesn't work. - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 15 - :language: py - The next step of ``main`` is to construct a :term:`Configurator` object: .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 16 + :lines: 7 :language: py ``settings`` is passed to the Configurator as a keyword argument with the dictionary values passed as the ``**settings`` argument. This will be a dictionary of settings parsed from the ``.ini`` file, which contains deployment-related values such as ``pyramid.reload_templates``, -``db_string``, etc. +``sqlalchemy.url``, and so on. -Next, include :term:`Chameleon` templating bindings so that we can use -renderers with the ``.pt`` extension within our project. +Next include :term:`Jinja2` templating bindings so that we can use renderers +with the ``.jinja2`` extension within our project. .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 17 + :lines: 8 + :language: py + +Next include the module ``meta`` from the package ``models`` using a dotted +Python path. + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 9 :language: py ``main`` now calls :meth:`pyramid.config.Configurator.add_static_view` with two arguments: ``static`` (the name), and ``static`` (the path): .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 18 + :lines: 10 :language: py This registers a static resource view which will match any URL that starts @@ -112,11 +91,11 @@ via the :meth:`pyramid.config.Configurator.add_route` method that will be used when the URL is ``/``: .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 19 + :lines: 11 :language: py -Since this route has a ``pattern`` equaling ``/`` it is the route that will -be matched when the URL ``/`` is visited, e.g. ``http://localhost:6543/``. +Since this route has a ``pattern`` equaling ``/``, it is the route that will +be matched when the URL ``/`` is visited, e.g., ``http://localhost:6543/``. ``main`` next calls the ``scan`` method of the configurator (:meth:`pyramid.config.Configurator.scan`), which will recursively scan our @@ -126,10 +105,10 @@ view configuration will be registered, which will allow one of our application URLs to be mapped to some code. .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 20 + :lines: 12 :language: py -Finally, ``main`` is finished configuring things, so it uses the +Finally ``main`` is finished configuring things, so it uses the :meth:`pyramid.config.Configurator.make_wsgi_app` method to return a :term:`WSGI` application: @@ -184,6 +163,39 @@ inform the user about possible actions to take to solve the problem. Content Models with ``models.py`` --------------------------------- +.. START moved from Application configuration with ``__init__.py``. This + section is a WIP, and needs to be updated using the new models package. + +The main function first creates a :term:`SQLAlchemy` database engine using +:func:`sqlalchemy.engine_from_config` from the ``sqlalchemy.`` prefixed +settings in the ``development.ini`` file's ``[app:main]`` section. +This will be a URI (something like ``sqlite://``): + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 13 + :language: py + +``main`` then initializes our SQLAlchemy session object, passing it the +engine: + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 14 + :language: py + +``main`` subsequently initializes our SQLAlchemy declarative ``Base`` object, +assigning the engine we created to the ``bind`` attribute of it's +``metadata`` object. This allows table definitions done imperatively +(instead of declaratively, via a class statement) to work. We won't use any +such tables in our application, but if you add one later, long after you've +forgotten about this tutorial, you won't be left scratching your head when it +doesn't work. + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 15 + :language: py + +.. END moved from Application configuration with ``__init__.py`` + In a SQLAlchemy-based application, a *model* object is an object composed by querying the SQL database. The ``models.py`` file is where the ``alchemy`` scaffold put the classes that implement our models. diff --git a/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py b/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py index 867049e4f..7994bbfa8 100644 --- a/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py +++ b/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py @@ -1,20 +1,12 @@ from pyramid.config import Configurator -from sqlalchemy import engine_from_config - -from .models import ( - DBSession, - Base, - ) def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ - engine = engine_from_config(settings, 'sqlalchemy.') - DBSession.configure(bind=engine) - Base.metadata.bind = engine config = Configurator(settings=settings) - config.include('pyramid_chameleon') + config.include('pyramid_jinja2') + config.include('.models.meta') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() -- cgit v1.2.3 From 049e670aef9ea5611561546fd5c0e2dd6152b9b7 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 11 Nov 2015 21:09:15 -0800 Subject: Revert "update wiki2/src/basiclayout/tutorial" --- docs/quick_tour.rst | 4 +- docs/quick_tour/sqla_demo/development.ini | 4 +- docs/quick_tour/sqla_demo/production.ini | 2 +- docs/quick_tour/sqla_demo/setup.py | 11 +- docs/quick_tour/sqla_demo/sqla_demo.sqlite | Bin 0 -> 3072 bytes docs/quick_tour/sqla_demo/sqla_demo/__init__.py | 11 +- docs/quick_tour/sqla_demo/sqla_demo/models.py | 29 ++ .../sqla_demo/sqla_demo/models/__init__.py | 7 - docs/quick_tour/sqla_demo/sqla_demo/models/meta.py | 46 --- .../sqla_demo/sqla_demo/models/mymodel.py | 19 -- .../sqla_demo/sqla_demo/scripts/initializedb.py | 30 +- .../sqla_demo/sqla_demo/static/favicon.ico | Bin 0 -> 1406 bytes .../sqla_demo/sqla_demo/static/footerbg.png | Bin 0 -> 333 bytes .../sqla_demo/sqla_demo/static/headerbg.png | Bin 0 -> 203 bytes docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css | 8 + .../sqla_demo/sqla_demo/static/middlebg.png | Bin 0 -> 2797 bytes .../sqla_demo/sqla_demo/static/pylons.css | 372 +++++++++++++++++++++ .../sqla_demo/sqla_demo/static/pyramid-16x16.png | Bin 1319 -> 0 bytes .../sqla_demo/sqla_demo/static/pyramid-small.png | Bin 0 -> 7044 bytes .../sqla_demo/sqla_demo/static/pyramid.png | Bin 12901 -> 33055 bytes .../sqla_demo/sqla_demo/static/theme.css | 154 --------- .../sqla_demo/sqla_demo/static/theme.min.css | 1 - .../sqla_demo/sqla_demo/static/transparent.gif | Bin 0 -> 49 bytes .../sqla_demo/sqla_demo/templates/layout.jinja2 | 66 ---- .../sqla_demo/templates/mytemplate.jinja2 | 8 - .../sqla_demo/sqla_demo/templates/mytemplate.pt | 76 +++++ docs/quick_tour/sqla_demo/sqla_demo/tests.py | 68 +--- docs/quick_tour/sqla_demo/sqla_demo/views.py | 37 ++ .../sqla_demo/sqla_demo/views/__init__.py | 0 .../sqla_demo/sqla_demo/views/default.py | 35 -- docs/tutorials/wiki2/basiclayout.rst | 98 +++--- .../wiki2/src/basiclayout/development.ini | 4 +- .../tutorials/wiki2/src/basiclayout/production.ini | 2 +- .../wiki2/src/basiclayout/tutorial/__init__.py | 12 +- 34 files changed, 625 insertions(+), 479 deletions(-) create mode 100644 docs/quick_tour/sqla_demo/sqla_demo.sqlite create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models.py delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models/meta.py delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/theme.css delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/views.py delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/views/__init__.py delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo/views/default.py (limited to 'docs') diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index 87c6f1e1c..be5be2e36 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -818,14 +818,14 @@ The ORM eases the mapping of database structures into a programming language. SQLAlchemy uses "models" for this mapping. The scaffold generated a sample model: -.. literalinclude:: quick_tour/sqla_demo/sqla_demo/models/mymodel.py +.. literalinclude:: quick_tour/sqla_demo/sqla_demo/models.py :start-after: Start Sphinx Include :end-before: End Sphinx Include View code, which mediates the logic between web requests and the rest of the system, can then easily get at the data thanks to SQLAlchemy: -.. literalinclude:: quick_tour/sqla_demo/sqla_demo/views/default.py +.. literalinclude:: quick_tour/sqla_demo/sqla_demo/views.py :start-after: Start Sphinx Include :end-before: End Sphinx Include diff --git a/docs/quick_tour/sqla_demo/development.ini b/docs/quick_tour/sqla_demo/development.ini index 0db0950a0..174468abf 100644 --- a/docs/quick_tour/sqla_demo/development.ini +++ b/docs/quick_tour/sqla_demo/development.ini @@ -27,7 +27,7 @@ sqlalchemy.url = sqlite:///%(here)s/sqla_demo.sqlite [server:main] use = egg:waitress#main -host = 127.0.0.1 +host = 0.0.0.0 port = 6543 ### @@ -68,4 +68,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/sqla_demo/production.ini b/docs/quick_tour/sqla_demo/production.ini index 38f3b6318..dc0ba304f 100644 --- a/docs/quick_tour/sqla_demo/production.ini +++ b/docs/quick_tour/sqla_demo/production.ini @@ -59,4 +59,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/sqla_demo/setup.py b/docs/quick_tour/sqla_demo/setup.py index 312a97c06..ac2eed035 100644 --- a/docs/quick_tour/sqla_demo/setup.py +++ b/docs/quick_tour/sqla_demo/setup.py @@ -3,18 +3,15 @@ import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) -with open(os.path.join(here, 'README.txt')) as f: - README = f.read() -with open(os.path.join(here, 'CHANGES.txt')) as f: - CHANGES = f.read() +README = open(os.path.join(here, 'README.txt')).read() +CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() requires = [ 'pyramid', - 'pyramid_jinja2', - 'pyramid_debugtoolbar', - 'pyramid_tm', 'SQLAlchemy', 'transaction', + 'pyramid_tm', + 'pyramid_debugtoolbar', 'zope.sqlalchemy', 'waitress', ] diff --git a/docs/quick_tour/sqla_demo/sqla_demo.sqlite b/docs/quick_tour/sqla_demo/sqla_demo.sqlite new file mode 100644 index 000000000..fa6adb104 Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo.sqlite differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/__init__.py index 7994bbfa8..aac7c5e69 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/__init__.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/__init__.py @@ -1,12 +1,19 @@ from pyramid.config import Configurator +from sqlalchemy import engine_from_config + +from .models import ( + DBSession, + Base, + ) def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ + engine = engine_from_config(settings, 'sqlalchemy.') + DBSession.configure(bind=engine) + Base.metadata.bind = engine config = Configurator(settings=settings) - config.include('pyramid_jinja2') - config.include('.models.meta') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models.py b/docs/quick_tour/sqla_demo/sqla_demo/models.py new file mode 100644 index 000000000..3dfb40e58 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/models.py @@ -0,0 +1,29 @@ +from sqlalchemy import ( + Column, + Integer, + Text, + ) + +from sqlalchemy.ext.declarative import declarative_base + +from sqlalchemy.orm import ( + scoped_session, + sessionmaker, + ) + +from zope.sqlalchemy import ZopeTransactionExtension + +DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) +Base = declarative_base() + +# Start Sphinx Include +class MyModel(Base): + __tablename__ = 'models' + id = Column(Integer, primary_key=True) + name = Column(Text, unique=True) + value = Column(Integer) + + def __init__(self, name, value): + self.name = name + self.value = value + # End Sphinx Include diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py deleted file mode 100644 index 6ffc10a78..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/models/__init__.py +++ /dev/null @@ -1,7 +0,0 @@ -from sqlalchemy.orm import configure_mappers -# import all models classes here for sqlalchemy mappers -# to pick up -from .mymodel import MyModel # flake8: noqa - -# run configure mappers to ensure we avoid any race conditions -configure_mappers() diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/meta.py b/docs/quick_tour/sqla_demo/sqla_demo/models/meta.py deleted file mode 100644 index b72b45f9f..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/models/meta.py +++ /dev/null @@ -1,46 +0,0 @@ -from sqlalchemy import engine_from_config -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker -from sqlalchemy.schema import MetaData -import zope.sqlalchemy - -NAMING_CONVENTION = { - "ix": 'ix_%(column_0_label)s', - "uq": "uq_%(table_name)s_%(column_0_name)s", - "ck": "ck_%(table_name)s_%(constraint_name)s", - "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", - "pk": "pk_%(table_name)s" -} - -metadata = MetaData(naming_convention=NAMING_CONVENTION) -Base = declarative_base(metadata=metadata) - - -def includeme(config): - settings = config.get_settings() - dbmaker = get_dbmaker(get_engine(settings)) - - config.add_request_method( - lambda r: get_session(r.tm, dbmaker), - 'dbsession', - reify=True - ) - - config.include('pyramid_tm') - - -def get_session(transaction_manager, dbmaker): - dbsession = dbmaker() - zope.sqlalchemy.register(dbsession, - transaction_manager=transaction_manager) - return dbsession - - -def get_engine(settings, prefix='sqlalchemy.'): - return engine_from_config(settings, prefix) - - -def get_dbmaker(engine): - dbmaker = sessionmaker() - dbmaker.configure(bind=engine) - return dbmaker diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py b/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py deleted file mode 100644 index eb645bfe6..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/models/mymodel.py +++ /dev/null @@ -1,19 +0,0 @@ -from .meta import Base -from sqlalchemy import ( - Column, - Index, - Integer, - Text, -) - - -# Start Sphinx Include -class MyModel(Base): - __tablename__ = 'models' - id = Column(Integer, primary_key=True) - name = Column(Text) - value = Column(Integer) - # End Sphinx Include - - -Index('my_index', MyModel.name, unique=True, mysql_length=255) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py b/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py index f0d09729e..66feb3008 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py @@ -2,44 +2,36 @@ import os import sys import transaction +from sqlalchemy import engine_from_config + from pyramid.paster import ( get_appsettings, setup_logging, ) -from pyramid.scripts.common import parse_vars - -from ..models.meta import ( +from ..models import ( + DBSession, + MyModel, Base, - get_session, - get_engine, - get_dbmaker, ) -from ..models.mymodel import MyModel def usage(argv): cmd = os.path.basename(argv[0]) - print('usage: %s [var=value]\n' + print('usage: %s \n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): - if len(argv) < 2: + if len(argv) != 2: usage(argv) config_uri = argv[1] - options = parse_vars(argv[2:]) setup_logging(config_uri) - settings = get_appsettings(config_uri, options=options) - - engine = get_engine(settings) - dbmaker = get_dbmaker(engine) - - dbsession = get_session(transaction.manager, dbmaker) - + settings = get_appsettings(config_uri) + engine = engine_from_config(settings, 'sqlalchemy.') + DBSession.configure(bind=engine) Base.metadata.create_all(engine) - with transaction.manager: model = MyModel(name='one', value=1) - dbsession.add(model) + DBSession.add(model) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico b/docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico new file mode 100644 index 000000000..71f837c9e Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/favicon.ico differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png b/docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png new file mode 100644 index 000000000..1fbc873da Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/footerbg.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png b/docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png new file mode 100644 index 000000000..0596f2020 Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/headerbg.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css b/docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css new file mode 100644 index 000000000..b7c8493d8 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/static/ie6.css @@ -0,0 +1,8 @@ +* html img, +* html .png{position:relative;behavior:expression((this.runtimeStyle.behavior="none")&&(this.pngSet?this.pngSet=true:(this.nodeName == "IMG" && this.src.toLowerCase().indexOf('.png')>-1?(this.runtimeStyle.backgroundImage = "none", +this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "',sizingMethod='image')", +this.src = "static/transparent.gif"):(this.origBg = this.origBg? this.origBg :this.currentStyle.backgroundImage.toString().replace('url("','').replace('")',''), +this.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.origBg + "',sizingMethod='crop')", +this.runtimeStyle.backgroundImage = "none")),this.pngSet=true) +);} +#wrap{display:table;height:100%} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png b/docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png new file mode 100644 index 000000000..2369cfb7d Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/middlebg.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css b/docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css new file mode 100644 index 000000000..4b1c017cd --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/static/pylons.css @@ -0,0 +1,372 @@ +html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td +{ + margin: 0; + padding: 0; + border: 0; + outline: 0; + font-size: 100%; /* 16px */ + vertical-align: baseline; + background: transparent; +} + +body +{ + line-height: 1; +} + +ol, ul +{ + list-style: none; +} + +blockquote, q +{ + quotes: none; +} + +blockquote:before, blockquote:after, q:before, q:after +{ + content: ''; + content: none; +} + +:focus +{ + outline: 0; +} + +ins +{ + text-decoration: none; +} + +del +{ + text-decoration: line-through; +} + +table +{ + border-collapse: collapse; + border-spacing: 0; +} + +sub +{ + vertical-align: sub; + font-size: smaller; + line-height: normal; +} + +sup +{ + vertical-align: super; + font-size: smaller; + line-height: normal; +} + +ul, menu, dir +{ + display: block; + list-style-type: disc; + margin: 1em 0; + padding-left: 40px; +} + +ol +{ + display: block; + list-style-type: decimal-leading-zero; + margin: 1em 0; + padding-left: 40px; +} + +li +{ + display: list-item; +} + +ul ul, ul ol, ul dir, ul menu, ul dl, ol ul, ol ol, ol dir, ol menu, ol dl, dir ul, dir ol, dir dir, dir menu, dir dl, menu ul, menu ol, menu dir, menu menu, menu dl, dl ul, dl ol, dl dir, dl menu, dl dl +{ + margin-top: 0; + margin-bottom: 0; +} + +ol ul, ul ul, menu ul, dir ul, ol menu, ul menu, menu menu, dir menu, ol dir, ul dir, menu dir, dir dir +{ + list-style-type: circle; +} + +ol ol ul, ol ul ul, ol menu ul, ol dir ul, ol ol menu, ol ul menu, ol menu menu, ol dir menu, ol ol dir, ol ul dir, ol menu dir, ol dir dir, ul ol ul, ul ul ul, ul menu ul, ul dir ul, ul ol menu, ul ul menu, ul menu menu, ul dir menu, ul ol dir, ul ul dir, ul menu dir, ul dir dir, menu ol ul, menu ul ul, menu menu ul, menu dir ul, menu ol menu, menu ul menu, menu menu menu, menu dir menu, menu ol dir, menu ul dir, menu menu dir, menu dir dir, dir ol ul, dir ul ul, dir menu ul, dir dir ul, dir ol menu, dir ul menu, dir menu menu, dir dir menu, dir ol dir, dir ul dir, dir menu dir, dir dir dir +{ + list-style-type: square; +} + +.hidden +{ + display: none; +} + +p +{ + line-height: 1.5em; +} + +h1 +{ + font-size: 1.75em; + line-height: 1.7em; + font-family: helvetica, verdana; +} + +h2 +{ + font-size: 1.5em; + line-height: 1.7em; + font-family: helvetica, verdana; +} + +h3 +{ + font-size: 1.25em; + line-height: 1.7em; + font-family: helvetica, verdana; +} + +h4 +{ + font-size: 1em; + line-height: 1.7em; + font-family: helvetica, verdana; +} + +html, body +{ + width: 100%; + height: 100%; +} + +body +{ + margin: 0; + padding: 0; + background-color: #fff; + position: relative; + font: 16px/24px NobileRegular, "Lucida Grande", Lucida, Verdana, sans-serif; +} + +a +{ + color: #1b61d6; + text-decoration: none; +} + +a:hover +{ + color: #e88f00; + text-decoration: underline; +} + +body h1, body h2, body h3, body h4, body h5, body h6 +{ + font-family: NeutonRegular, "Lucida Grande", Lucida, Verdana, sans-serif; + font-weight: 400; + color: #373839; + font-style: normal; +} + +#wrap +{ + min-height: 100%; +} + +#header, #footer +{ + width: 100%; + color: #fff; + height: 40px; + position: absolute; + text-align: center; + line-height: 40px; + overflow: hidden; + font-size: 12px; + vertical-align: middle; +} + +#header +{ + background: #000; + top: 0; + font-size: 14px; +} + +#footer +{ + bottom: 0; + background: #000 url(footerbg.png) repeat-x 0 top; + position: relative; + margin-top: -40px; + clear: both; +} + +.header, .footer +{ + width: 750px; + margin-right: auto; + margin-left: auto; +} + +.wrapper +{ + width: 100%; +} + +#top, #top-small, #bottom +{ + width: 100%; +} + +#top +{ + color: #000; + height: 230px; + background: #fff url(headerbg.png) repeat-x 0 top; + position: relative; +} + +#top-small +{ + color: #000; + height: 60px; + background: #fff url(headerbg.png) repeat-x 0 top; + position: relative; +} + +#bottom +{ + color: #222; + background-color: #fff; +} + +.top, .top-small, .middle, .bottom +{ + width: 750px; + margin-right: auto; + margin-left: auto; +} + +.top +{ + padding-top: 40px; +} + +.top-small +{ + padding-top: 10px; +} + +#middle +{ + width: 100%; + height: 100px; + background: url(middlebg.png) repeat-x; + border-top: 2px solid #fff; + border-bottom: 2px solid #b2b2b2; +} + +.app-welcome +{ + margin-top: 25px; +} + +.app-name +{ + color: #000; + font-weight: 700; +} + +.bottom +{ + padding-top: 50px; +} + +#left +{ + width: 350px; + float: left; + padding-right: 25px; +} + +#right +{ + width: 350px; + float: right; + padding-left: 25px; +} + +.align-left +{ + text-align: left; +} + +.align-right +{ + text-align: right; +} + +.align-center +{ + text-align: center; +} + +ul.links +{ + margin: 0; + padding: 0; +} + +ul.links li +{ + list-style-type: none; + font-size: 14px; +} + +form +{ + border-style: none; +} + +fieldset +{ + border-style: none; +} + +input +{ + color: #222; + border: 1px solid #ccc; + font-family: sans-serif; + font-size: 12px; + line-height: 16px; +} + +input[type=text], input[type=password] +{ + width: 205px; +} + +input[type=submit] +{ + background-color: #ddd; + font-weight: 700; +} + +/*Opera Fix*/ +body:before +{ + content: ""; + height: 100%; + float: left; + width: 0; + margin-top: -32767px; +} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png deleted file mode 100644 index 979203112..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png new file mode 100644 index 000000000..a5bc0ade7 Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-small.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png index 4ab837be9..347e05549 100644 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png and b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css deleted file mode 100644 index 0f4b1a4d4..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css +++ /dev/null @@ -1,154 +0,0 @@ -@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700); -body { - font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; - font-weight: 300; - color: #ffffff; - background: #bc2131; -} -h1, -h2, -h3, -h4, -h5, -h6 { - font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; - font-weight: 300; -} -p { - font-weight: 300; -} -.font-normal { - font-weight: 400; -} -.font-semi-bold { - font-weight: 600; -} -.font-bold { - font-weight: 700; -} -.starter-template { - margin-top: 250px; -} -.starter-template .content { - margin-left: 10px; -} -.starter-template .content h1 { - margin-top: 10px; - font-size: 60px; -} -.starter-template .content h1 .smaller { - font-size: 40px; - color: #f2b7bd; -} -.starter-template .content .lead { - font-size: 25px; - color: #f2b7bd; -} -.starter-template .content .lead .font-normal { - color: #ffffff; -} -.starter-template .links { - float: right; - right: 0; - margin-top: 125px; -} -.starter-template .links ul { - display: block; - padding: 0; - margin: 0; -} -.starter-template .links ul li { - list-style: none; - display: inline; - margin: 0 10px; -} -.starter-template .links ul li:first-child { - margin-left: 0; -} -.starter-template .links ul li:last-child { - margin-right: 0; -} -.starter-template .links ul li.current-version { - color: #f2b7bd; - font-weight: 400; -} -.starter-template .links ul li a, a { - color: #f2b7bd; - text-decoration: underline; -} -.starter-template .links ul li a:hover, a:hover { - color: #ffffff; - text-decoration: underline; -} -.starter-template .links ul li .icon-muted { - color: #eb8b95; - margin-right: 5px; -} -.starter-template .links ul li:hover .icon-muted { - color: #ffffff; -} -.starter-template .copyright { - margin-top: 10px; - font-size: 0.9em; - color: #f2b7bd; - text-transform: lowercase; - float: right; - right: 0; -} -@media (max-width: 1199px) { - .starter-template .content h1 { - font-size: 45px; - } - .starter-template .content h1 .smaller { - font-size: 30px; - } - .starter-template .content .lead { - font-size: 20px; - } -} -@media (max-width: 991px) { - .starter-template { - margin-top: 0; - } - .starter-template .logo { - margin: 40px auto; - } - .starter-template .content { - margin-left: 0; - text-align: center; - } - .starter-template .content h1 { - margin-bottom: 20px; - } - .starter-template .links { - float: none; - text-align: center; - margin-top: 60px; - } - .starter-template .copyright { - float: none; - text-align: center; - } -} -@media (max-width: 767px) { - .starter-template .content h1 .smaller { - font-size: 25px; - display: block; - } - .starter-template .content .lead { - font-size: 16px; - } - .starter-template .links { - margin-top: 40px; - } - .starter-template .links ul li { - display: block; - margin: 0; - } - .starter-template .links ul li .icon-muted { - display: none; - } - .starter-template .copyright { - margin-top: 20px; - } -} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css deleted file mode 100644 index 0d25de5b6..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css +++ /dev/null @@ -1 +0,0 @@ -@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700);body{font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:300;color:#fff;background:#bc2131}h1,h2,h3,h4,h5,h6{font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:300}p{font-weight:300}.font-normal{font-weight:400}.font-semi-bold{font-weight:600}.font-bold{font-weight:700}.starter-template{margin-top:250px}.starter-template .content{margin-left:10px}.starter-template .content h1{margin-top:10px;font-size:60px}.starter-template .content h1 .smaller{font-size:40px;color:#f2b7bd}.starter-template .content .lead{font-size:25px;color:#f2b7bd}.starter-template .content .lead .font-normal{color:#fff}.starter-template .links{float:right;right:0;margin-top:125px}.starter-template .links ul{display:block;padding:0;margin:0}.starter-template .links ul li{list-style:none;display:inline;margin:0 10px}.starter-template .links ul li:first-child{margin-left:0}.starter-template .links ul li:last-child{margin-right:0}.starter-template .links ul li.current-version{color:#f2b7bd;font-weight:400}.starter-template .links ul li a,a{color:#f2b7bd;text-decoration:underline}.starter-template .links ul li a:hover,a:hover{color:#fff;text-decoration:underline}.starter-template .links ul li .icon-muted{color:#eb8b95;margin-right:5px}.starter-template .links ul li:hover .icon-muted{color:#fff}.starter-template .copyright{margin-top:10px;font-size:.9em;color:#f2b7bd;text-transform:lowercase;float:right;right:0}@media (max-width:1199px){.starter-template .content h1{font-size:45px}.starter-template .content h1 .smaller{font-size:30px}.starter-template .content .lead{font-size:20px}}@media (max-width:991px){.starter-template{margin-top:0}.starter-template .logo{margin:40px auto}.starter-template .content{margin-left:0;text-align:center}.starter-template .content h1{margin-bottom:20px}.starter-template .links{float:none;text-align:center;margin-top:60px}.starter-template .copyright{float:none;text-align:center}}@media (max-width:767px){.starter-template .content h1 .smaller{font-size:25px;display:block}.starter-template .content .lead{font-size:16px}.starter-template .links{margin-top:40px}.starter-template .links ul li{display:block;margin:0}.starter-template .links ul li .icon-muted{display:none}.starter-template .copyright{margin-top:20px}} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif b/docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif new file mode 100644 index 000000000..0341802e5 Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/transparent.gif differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 b/docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 deleted file mode 100644 index 76a098122..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/templates/layout.jinja2 +++ /dev/null @@ -1,66 +0,0 @@ - - - - - - - - - - - Alchemy Scaffold for The Pyramid Web Framework - - - - - - - - - - - - - -
-
-
-
- -
-
- {% block content %} -

No content

- {% endblock content %} -
-
-
- -
-
- -
-
-
- - - - - - - - diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 deleted file mode 100644 index bb622bf5a..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.jinja2 +++ /dev/null @@ -1,8 +0,0 @@ -{% extends "layout.jinja2" %} - -{% block content %} -
-

Pyramid Alchemy scaffold

-

Welcome to {{project}}, an application generated by
the Pyramid Web Framework 1.7.dev0.

-
-{% endblock content %} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt new file mode 100644 index 000000000..321c0f5fb --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt @@ -0,0 +1,76 @@ + + + + The Pyramid Web Framework + + + + + + + + + + +
+
+
+
pyramid
+
+
+
+
+

+ Welcome to ${project}, an application generated by
+ the Pyramid web framework. +

+
+
+
+
+
+

Search documentation

+
+ + +
+
+ +
+
+
+ + + diff --git a/docs/quick_tour/sqla_demo/sqla_demo/tests.py b/docs/quick_tour/sqla_demo/sqla_demo/tests.py index b6b6fdf4d..6fef6d695 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/tests.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/tests.py @@ -3,63 +3,31 @@ import transaction from pyramid import testing +from .models import DBSession -def dummy_request(dbsession): - return testing.DummyRequest(dbsession=dbsession) - -class BaseTest(unittest.TestCase): +class TestMyView(unittest.TestCase): def setUp(self): - self.config = testing.setUp(settings={ - 'sqlalchemy.url': 'sqlite:///:memory:' - }) - self.config.include('.models.meta') - settings = self.config.get_settings() - - from .models.meta import ( - get_session, - get_engine, - get_dbmaker, + self.config = testing.setUp() + from sqlalchemy import create_engine + engine = create_engine('sqlite://') + from .models import ( + Base, + MyModel, ) - - self.engine = get_engine(settings) - dbmaker = get_dbmaker(self.engine) - - self.session = get_session(transaction.manager, dbmaker) - - def init_database(self): - from .models.meta import Base - Base.metadata.create_all(self.engine) + DBSession.configure(bind=engine) + Base.metadata.create_all(engine) + with transaction.manager: + model = MyModel(name='one', value=55) + DBSession.add(model) def tearDown(self): - from .models.meta import Base - + DBSession.remove() testing.tearDown() - transaction.abort() - Base.metadata.create_all(self.engine) - - -class TestMyViewSuccessCondition(BaseTest): - def setUp(self): - super(TestMyViewSuccessCondition, self).setUp() - self.init_database() - - from .models.mymodel import MyModel - - model = MyModel(name='one', value=55) - self.session.add(model) - - def test_passing_view(self): - from .views.default import my_view - info = my_view(dummy_request(self.session)) + def test_it(self): + from .views import my_view + request = testing.DummyRequest() + info = my_view(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'sqla_demo') - - -class TestMyViewFailureCondition(BaseTest): - - def test_failing_view(self): - from .views.default import my_view - info = my_view(dummy_request(self.session)) - self.assertEqual(info.status_int, 500) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views.py b/docs/quick_tour/sqla_demo/sqla_demo/views.py new file mode 100644 index 000000000..768a7e42e --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/views.py @@ -0,0 +1,37 @@ +from pyramid.response import Response +from pyramid.view import view_config + +from sqlalchemy.exc import DBAPIError + +from .models import ( + DBSession, + MyModel, + ) + + +@view_config(route_name='home', renderer='templates/mytemplate.pt') +def my_view(request): + try: + # Start Sphinx Include + one = DBSession.query(MyModel).filter(MyModel.name == 'one').first() + # End Sphinx Include + except DBAPIError: + return Response(conn_err_msg, content_type='text/plain', status_int=500) + return {'one': one, 'project': 'sqla_demo'} + +conn_err_msg = """\ +Pyramid is having a problem using your SQL database. The problem +might be caused by one of the following things: + +1. You may need to run the "initialize_sqla_demo_db" script + to initialize your database tables. Check your virtual + environment's "bin" directory for this script and try to run it. + +2. Your database server may not be running. Check that the + database server referred to by the "sqlalchemy.url" setting in + your "development.ini" file is running. + +After you fix the problem, please restart the Pyramid application to +try it again. +""" + diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/views/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views/default.py b/docs/quick_tour/sqla_demo/sqla_demo/views/default.py deleted file mode 100644 index e5e70cf9d..000000000 --- a/docs/quick_tour/sqla_demo/sqla_demo/views/default.py +++ /dev/null @@ -1,35 +0,0 @@ -from pyramid.response import Response -from pyramid.view import view_config - -from sqlalchemy.exc import DBAPIError - -from ..models.mymodel import MyModel - - -@view_config(route_name='home', renderer='../templates/mytemplate.jinja2') -def my_view(request): - try: - query = request.dbsession.query(MyModel) - # Start Sphinx Include - one = query.filter(MyModel.name == 'one').first() - # End Sphinx Include - except DBAPIError: - return Response(db_err_msg, content_type='text/plain', status_int=500) - return {'one': one, 'project': 'sqla_demo'} - - -db_err_msg = """\ -Pyramid is having a problem using your SQL database. The problem -might be caused by one of the following things: - -1. You may need to run the "initialize_sqla_demo_db" script - to initialize your database tables. Check your virtual - environment's "bin" directory for this script and try to run it. - -2. Your database server may not be running. Check that the - database server referred to by the "sqlalchemy.url" setting in - your "development.ini" file is running. - -After you fix the problem, please restart the Pyramid application to -try it again. -""" diff --git a/docs/tutorials/wiki2/basiclayout.rst b/docs/tutorials/wiki2/basiclayout.rst index 72b2bc26b..695d7f15b 100644 --- a/docs/tutorials/wiki2/basiclayout.rst +++ b/docs/tutorials/wiki2/basiclayout.rst @@ -12,12 +12,12 @@ Application configuration with ``__init__.py`` A directory on disk can be turned into a Python :term:`package` by containing an ``__init__.py`` file. Even if empty, this marks a directory as a Python -package. We use ``__init__.py`` both as a marker, indicating the directory in -which it's contained is a package, and to contain application configuration +package. We use ``__init__.py`` both as a marker, indicating the directory +in which it's contained is a package, and to contain application configuration code. -Open ``tutorial/tutorial/__init__.py``. It should already contain the -following: +Open ``tutorial/tutorial/__init__.py``. It should already contain +the following: .. literalinclude:: src/basiclayout/tutorial/__init__.py :linenos: @@ -43,37 +43,58 @@ When you invoke the ``pserve development.ini`` command, the ``main`` function above is executed. It accepts some settings and returns a :term:`WSGI` application. (See :ref:`startup_chapter` for more about ``pserve``.) +The main function first creates a :term:`SQLAlchemy` database engine using +:func:`sqlalchemy.engine_from_config` from the ``sqlalchemy.`` prefixed +settings in the ``development.ini`` file's ``[app:main]`` section. +This will be a URI (something like ``sqlite://``): + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 13 + :language: py + +``main`` then initializes our SQLAlchemy session object, passing it the +engine: + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 14 + :language: py + +``main`` subsequently initializes our SQLAlchemy declarative ``Base`` object, +assigning the engine we created to the ``bind`` attribute of it's +``metadata`` object. This allows table definitions done imperatively +(instead of declaratively, via a class statement) to work. We won't use any +such tables in our application, but if you add one later, long after you've +forgotten about this tutorial, you won't be left scratching your head when it +doesn't work. + + .. literalinclude:: src/basiclayout/tutorial/__init__.py + :lines: 15 + :language: py + The next step of ``main`` is to construct a :term:`Configurator` object: .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 7 + :lines: 16 :language: py ``settings`` is passed to the Configurator as a keyword argument with the dictionary values passed as the ``**settings`` argument. This will be a dictionary of settings parsed from the ``.ini`` file, which contains deployment-related values such as ``pyramid.reload_templates``, -``sqlalchemy.url``, and so on. - -Next include :term:`Jinja2` templating bindings so that we can use renderers -with the ``.jinja2`` extension within our project. - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 8 - :language: py +``db_string``, etc. -Next include the module ``meta`` from the package ``models`` using a dotted -Python path. +Next, include :term:`Chameleon` templating bindings so that we can use +renderers with the ``.pt`` extension within our project. .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 9 + :lines: 17 :language: py ``main`` now calls :meth:`pyramid.config.Configurator.add_static_view` with two arguments: ``static`` (the name), and ``static`` (the path): .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 10 + :lines: 18 :language: py This registers a static resource view which will match any URL that starts @@ -91,11 +112,11 @@ via the :meth:`pyramid.config.Configurator.add_route` method that will be used when the URL is ``/``: .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 11 + :lines: 19 :language: py -Since this route has a ``pattern`` equaling ``/``, it is the route that will -be matched when the URL ``/`` is visited, e.g., ``http://localhost:6543/``. +Since this route has a ``pattern`` equaling ``/`` it is the route that will +be matched when the URL ``/`` is visited, e.g. ``http://localhost:6543/``. ``main`` next calls the ``scan`` method of the configurator (:meth:`pyramid.config.Configurator.scan`), which will recursively scan our @@ -105,10 +126,10 @@ view configuration will be registered, which will allow one of our application URLs to be mapped to some code. .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 12 + :lines: 20 :language: py -Finally ``main`` is finished configuring things, so it uses the +Finally, ``main`` is finished configuring things, so it uses the :meth:`pyramid.config.Configurator.make_wsgi_app` method to return a :term:`WSGI` application: @@ -163,39 +184,6 @@ inform the user about possible actions to take to solve the problem. Content Models with ``models.py`` --------------------------------- -.. START moved from Application configuration with ``__init__.py``. This - section is a WIP, and needs to be updated using the new models package. - -The main function first creates a :term:`SQLAlchemy` database engine using -:func:`sqlalchemy.engine_from_config` from the ``sqlalchemy.`` prefixed -settings in the ``development.ini`` file's ``[app:main]`` section. -This will be a URI (something like ``sqlite://``): - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 13 - :language: py - -``main`` then initializes our SQLAlchemy session object, passing it the -engine: - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 14 - :language: py - -``main`` subsequently initializes our SQLAlchemy declarative ``Base`` object, -assigning the engine we created to the ``bind`` attribute of it's -``metadata`` object. This allows table definitions done imperatively -(instead of declaratively, via a class statement) to work. We won't use any -such tables in our application, but if you add one later, long after you've -forgotten about this tutorial, you won't be left scratching your head when it -doesn't work. - - .. literalinclude:: src/basiclayout/tutorial/__init__.py - :lines: 15 - :language: py - -.. END moved from Application configuration with ``__init__.py`` - In a SQLAlchemy-based application, a *model* object is an object composed by querying the SQL database. The ``models.py`` file is where the ``alchemy`` scaffold put the classes that implement our models. diff --git a/docs/tutorials/wiki2/src/basiclayout/development.ini b/docs/tutorials/wiki2/src/basiclayout/development.ini index 99c4ff0fe..a9d53b296 100644 --- a/docs/tutorials/wiki2/src/basiclayout/development.ini +++ b/docs/tutorials/wiki2/src/basiclayout/development.ini @@ -27,7 +27,7 @@ sqlalchemy.url = sqlite:///%(here)s/tutorial.sqlite [server:main] use = egg:waitress#main -host = 127.0.0.1 +host = 0.0.0.0 port = 6543 ### @@ -68,4 +68,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s diff --git a/docs/tutorials/wiki2/src/basiclayout/production.ini b/docs/tutorials/wiki2/src/basiclayout/production.ini index 97acfbd7d..fa94c1b3e 100644 --- a/docs/tutorials/wiki2/src/basiclayout/production.ini +++ b/docs/tutorials/wiki2/src/basiclayout/production.ini @@ -59,4 +59,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s diff --git a/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py b/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py index 7994bbfa8..867049e4f 100644 --- a/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py +++ b/docs/tutorials/wiki2/src/basiclayout/tutorial/__init__.py @@ -1,12 +1,20 @@ from pyramid.config import Configurator +from sqlalchemy import engine_from_config + +from .models import ( + DBSession, + Base, + ) def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ + engine = engine_from_config(settings, 'sqlalchemy.') + DBSession.configure(bind=engine) + Base.metadata.bind = engine config = Configurator(settings=settings) - config.include('pyramid_jinja2') - config.include('.models.meta') + config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() -- cgit v1.2.3 From 31f3d86d3bf5db3c4aa5085c7b7a4d6396f29931 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 12 Nov 2015 00:55:38 -0600 Subject: complete cache buster docs using manifest example --- docs/api/static.rst | 3 + docs/glossary.rst | 4 ++ docs/narr/assets.rst | 183 ++++++++++++++++++++++----------------------------- 3 files changed, 84 insertions(+), 106 deletions(-) (limited to 'docs') diff --git a/docs/api/static.rst b/docs/api/static.rst index e6d6e4618..f3727e197 100644 --- a/docs/api/static.rst +++ b/docs/api/static.rst @@ -9,6 +9,9 @@ :members: :inherited-members: + .. autoclass:: ManifestCacheBuster + :members: + .. autoclass:: QueryStringCacheBuster :members: diff --git a/docs/glossary.rst b/docs/glossary.rst index 9c0ea8598..b4bb36421 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -1089,3 +1089,7 @@ Glossary data in a Redis database. See https://pypi.python.org/pypi/pyramid_redis_sessions for more information. + cache busting + A technique used when serving a cacheable static asset in order to force + a client to query the new version of the asset. See :ref:`cache_busting` + for more information. diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 397e0258d..d36fa49c0 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -356,14 +356,14 @@ may change, and then you'll want the client to load a new copy of the asset. Under normal circumstances you'd just need to wait for the client's cached copy to expire before they get the new version of the static resource. -A commonly used workaround to this problem is a technique known as "cache -busting". Cache busting schemes generally involve generating a URL for a -static asset that changes when the static asset changes. This way headers can -be sent along with the static asset instructing the client to cache the asset -for a very long time. When a static asset is changed, the URL used to refer to -it in a web page also changes, so the client sees it as a new resource and -requests the asset, regardless of any caching policy set for the resource's old -URL. +A commonly used workaround to this problem is a technique known as +:term:`cache busting`. Cache busting schemes generally involve generating a +URL for a static asset that changes when the static asset changes. This way +headers can be sent along with the static asset instructing the client to cache +the asset for a very long time. When a static asset is changed, the URL used +to refer to it in a web page also changes, so the client sees it as a new +resource and requests the asset, regardless of any caching policy set for the +resource's old URL. :app:`Pyramid` can be configured to produce cache busting URLs for static assets by passing the optional argument, ``cachebust`` to @@ -397,7 +397,7 @@ view to set headers instructing clients to cache the asset for ten years, unless the ``cache_max_age`` argument is also passed, in which case that value is used. -.. warning:: +.. note:: Cache busting is an inherently complex topic as it integrates the asset pipeline and the web application. It is expected and desired that @@ -429,16 +429,14 @@ arbitrary token you provide to the query string of the asset's URL. This is almost never what you want in production as it does not allow fine-grained busting of individual assets. - In order to implement your own cache buster, you can write your own class from scratch which implements the :class:`~pyramid.interfaces.ICacheBuster` interface. Alternatively you may choose to subclass one of the existing implementations. One of the most likely scenarios is you'd want to change the -way the asset token is generated. To do this just subclass either -:class:`~pyramid.static.PathSegmentCacheBuster` or +way the asset token is generated. To do this just subclass :class:`~pyramid.static.QueryStringCacheBuster` and define a -``tokenize(pathspec)`` method. Here is an example which just uses Git to get -the hash of the currently checked out code: +``tokenize(pathspec)`` method. Here is an example which uses Git to get +the hash of the current commit: .. code-block:: python :linenos: @@ -466,26 +464,60 @@ the hash of the currently checked out code: Choosing a Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~ -The default cache buster implementation, -:class:`~pyramid.static.PathSegmentMd5CacheBuster`, works very well assuming -that you're using :app:`Pyramid` to serve your static assets. The md5 checksum -is fine grained enough that browsers should only request new versions of -specific assets that have changed. Many caching HTTP proxies will fail to -cache a resource if the URL contains a query string. In general, therefore, -you should prefer a cache busting strategy which modifies the path segment to a -strategy which adds a query string. - -It is possible, however, that your static assets are being served by another -web server or externally on a CDN. In these cases modifying the path segment -for a static asset URL would cause the external service to fail to find the -asset, causing your customer to get a 404. In these cases you would need to -fall back to a cache buster which adds a query string. It is even possible -that there isn't a copy of your static assets available to the :app:`Pyramid` -application, so a cache busting implementation that generates md5 checksums -would fail since it can't access the assets. In such a case, -:class:`~pyramid.static.QueryStringConstantCacheBuster` is a reasonable -fallback. The following code would set up a cachebuster that just uses the -time at start up as a cachebust token: +Many caching HTTP proxies will fail to cache a resource if the URL contains +a query string. Therefore, in general, you should prefer a cache busting +strategy which modifies the path segment rather than methods which add a +token to the query string. + +You will need to consider whether the :app:`Pyramid` application will be +serving your static assets, whether you are using an external asset pipeline +to handle rewriting urls internal to the css/javascript, and how fine-grained +do you want the cache busting tokens to be. + +In many cases you will want to host the static assets on another web server +or externally on a CDN. In these cases your :app:`Pyramid` application may not +even have access to a copy of the static assets. In order to cache bust these +assets you will need some information about them. + +If you are using an external asset pipeline to generate your static files you +should consider using the :class:`~pyramid.static.ManifestCacheBuster`. +This cache buster can load a standard JSON formatted file generated by your +pipeline and use it to cache bust the assets. This has many performance +advantages as :app:`Pyramid` does not need to look at the files to generate +any cache busting tokens, but still supports fine-grained per-file tokens. + +Assuming an example ``manifest.json`` like: + +.. code-block:: json + + { + "css/main.css": "css/main-678b7c80.css", + "images/background.png": "images/background-a8169106.png" + } + +The following code would set up a cachebuster: + +.. code-block:: python + :linenos: + + from pyramid.path import AssetResolver + from pyramid.static import ManifestCacheBuster + + resolver = AssetResolver() + manifest = resolver.resolve('myapp:static/manifest.json') + config.add_static_view( + name='http://mycdn.example.com/', + path='mypackage:static', + cachebust=ManifestCacheBuster(manifest.abspath())) + +A simpler approach is to use the +:class:`~pyramid.static.QueryStringConstantCacheBuster` to generate a global +token that will bust all of the assets at once. The advantage of this strategy +is that it is simple and by using the query string there doesn't need to be +any shared information between your application and the static assets. + +The following code would set up a cachebuster that just uses the time at +start up as a cachebust token: .. code-block:: python :linenos: @@ -496,7 +528,7 @@ time at start up as a cachebust token: config.add_static_view( name='http://mycdn.example.com/', path='mypackage:static', - cachebust=QueryStringConstantCacheBuster(str(time.time()))) + cachebust=QueryStringConstantCacheBuster(str(int(time.time())))) .. index:: single: static assets view @@ -508,85 +540,24 @@ Often one needs to refer to images and other static assets inside CSS and JavaScript files. If cache busting is active, the final static asset URL is not available until the static assets have been assembled. These URLs cannot be handwritten. Thus, when having static asset references in CSS and JavaScript, -one needs to perform one of the following tasks. +one needs to perform one of the following tasks: * Process the files by using a precompiler which rewrites URLs to their final - cache busted form. + cache busted form. Then, you can use the + :class:`~pyramid.static.ManifestCacheBuster` to synchronize your asset + pipeline with :app:`Pyramid`, allowing the pipeline to have full control + over the final URLs of your assets. * Templatize JS and CSS, and call ``request.static_url()`` inside their template code. * Pass static URL references to CSS and JavaScript via other means. -Below are some simple approaches for CSS and JS programming which consider -asset cache busting. These approaches do not require additional tools or -packages. - -Relative cache busted URLs in CSS -+++++++++++++++++++++++++++++++++ - -Consider a CSS file ``/static/theme/css/site.css`` which contains the following -CSS code. - -.. code-block:: css - - body { - background: url(/static/theme/img/background.jpg); - } - -Any changes to ``background.jpg`` would not appear to the visitor because the -URL path is not cache busted as it is. Instead we would have to construct an -URL to the background image with the default ``PathSegmentCacheBuster`` cache -busting mechanism:: - - https://site/static/1eeb262c717/theme/img/background.jpg - -Every time the image is updated, the URL would need to be changed. It is not -practical to write this non-human readable URL into a CSS file. - -However, the CSS file itself is cache busted and is located under the path for -static assets. This lets us use relative references in our CSS to cache bust -the image. - -.. code-block:: css - - body { - background: url(../img/background.jpg); - } - -The browser would interpret this as having the CSS file hash in URL:: - - https://site/static/ab234b262c71/theme/css/../img/background.jpg - -The downside of this approach is that if the background image changes, one -needs to bump the CSS file. The CSS file hash change signals the caches that -the relative URL to the image in the CSS has been changed. When updating CSS -and related image assets, updates usually happen hand in hand, so this does not -add extra effort to theming workflow. - -Passing cache busted URLs to JavaScript -+++++++++++++++++++++++++++++++++++++++ - -For JavaScript, one can pass static asset URLs as function arguments or -globals. The globals can be generated in page template code, having access to -the ``request.static_url()`` function. - -Below is a simple example of passing a cached busted image URL in the Jinja2 -template language. Put the following code into the ```` section of the -relevant page. - -.. code-block:: html - - - -Then in your main ``site.js`` file, put the following code. - -.. code-block:: javascript - - var image = new Image(window.assets.backgroundImage); +If your CSS and JavaScript assets use URLs to reference other assets it is +recommended that you implement an external asset pipeline that can rewrite the +generated static files with new URLs containing cache busting tokens. The +machinery inside :app:`Pyramid` will not help with this step as it has very +little knowledge of the asset types your application may use. .. _advanced_static: -- cgit v1.2.3 From 6f4e97603c2562914567a85bf18187299c3b543b Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 12 Nov 2015 20:04:28 -0600 Subject: Revert "fix/remove-default-cachebusters" This reverts commit 7410250313f893e5952bb2697324a4d4e3d47d22. This reverts commit cbec33b898efffbfa6acaf91cae45ec0daed4d7a. This reverts commit 345ca3052c395545b90fef9104a16eed5ab051a5, reversing changes made to 47162533af84bb8d26db6d1c9ba1e63d70e9070f. --- docs/api/static.rst | 8 +- docs/glossary.rst | 4 - docs/narr/assets.rst | 257 +++++++++++++++++++++++++++++---------------------- 3 files changed, 155 insertions(+), 114 deletions(-) (limited to 'docs') diff --git a/docs/api/static.rst b/docs/api/static.rst index f3727e197..b6b279139 100644 --- a/docs/api/static.rst +++ b/docs/api/static.rst @@ -9,11 +9,17 @@ :members: :inherited-members: - .. autoclass:: ManifestCacheBuster + .. autoclass:: PathSegmentCacheBuster :members: .. autoclass:: QueryStringCacheBuster :members: + .. autoclass:: PathSegmentMd5CacheBuster + :members: + + .. autoclass:: QueryStringMd5CacheBuster + :members: + .. autoclass:: QueryStringConstantCacheBuster :members: diff --git a/docs/glossary.rst b/docs/glossary.rst index b4bb36421..9c0ea8598 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -1089,7 +1089,3 @@ Glossary data in a Redis database. See https://pypi.python.org/pypi/pyramid_redis_sessions for more information. - cache busting - A technique used when serving a cacheable static asset in order to force - a client to query the new version of the asset. See :ref:`cache_busting` - for more information. diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index d36fa49c0..020794062 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -356,14 +356,14 @@ may change, and then you'll want the client to load a new copy of the asset. Under normal circumstances you'd just need to wait for the client's cached copy to expire before they get the new version of the static resource. -A commonly used workaround to this problem is a technique known as -:term:`cache busting`. Cache busting schemes generally involve generating a -URL for a static asset that changes when the static asset changes. This way -headers can be sent along with the static asset instructing the client to cache -the asset for a very long time. When a static asset is changed, the URL used -to refer to it in a web page also changes, so the client sees it as a new -resource and requests the asset, regardless of any caching policy set for the -resource's old URL. +A commonly used workaround to this problem is a technique known as "cache +busting". Cache busting schemes generally involve generating a URL for a +static asset that changes when the static asset changes. This way headers can +be sent along with the static asset instructing the client to cache the asset +for a very long time. When a static asset is changed, the URL used to refer to +it in a web page also changes, so the client sees it as a new resource and +requests the asset, regardless of any caching policy set for the resource's old +URL. :app:`Pyramid` can be configured to produce cache busting URLs for static assets by passing the optional argument, ``cachebust`` to @@ -372,38 +372,30 @@ assets by passing the optional argument, ``cachebust`` to .. code-block:: python :linenos: - import time - from pyramid.static import QueryStringConstantCacheBuster - # config is an instance of pyramid.config.Configurator - config.add_static_view( - name='static', path='mypackage:folder/static', - cachebust=QueryStringConstantCacheBuster(str(int(time.time()))), - ) + config.add_static_view(name='static', path='mypackage:folder/static', + cachebust=True) Setting the ``cachebust`` argument instructs :app:`Pyramid` to use a cache -busting scheme which adds the curent time for a static asset to the query -string in the asset's URL: +busting scheme which adds the md5 checksum for a static asset as a path segment +in the asset's URL: .. code-block:: python :linenos: js_url = request.static_url('mypackage:folder/static/js/myapp.js') - # Returns: 'http://www.example.com/static/js/myapp.js?x=1445318121' + # Returns: 'http://www.example.com/static/c9658b3c0a314a1ca21e5988e662a09e/js/myapp.js' -When the web server restarts, the time constant will change and therefore so -will its URL. Supplying the ``cachebust`` argument also causes the static -view to set headers instructing clients to cache the asset for ten years, -unless the ``cache_max_age`` argument is also passed, in which case that -value is used. +When the asset changes, so will its md5 checksum, and therefore so will its +URL. Supplying the ``cachebust`` argument also causes the static view to set +headers instructing clients to cache the asset for ten years, unless the +``cache_max_age`` argument is also passed, in which case that value is used. .. note:: - Cache busting is an inherently complex topic as it integrates the asset - pipeline and the web application. It is expected and desired that - application authors will write their own cache buster implementations - conforming to the properties of their own asset pipelines. See - :ref:`custom_cache_busters` for information on writing your own. + md5 checksums are cached in RAM, so if you change a static resource without + restarting your application, you may still generate URLs with a stale md5 + checksum. Disabling the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -414,45 +406,65 @@ configured cache busters without changing calls to ``PYRAMID_PREVENT_CACHEBUST`` environment variable or the ``pyramid.prevent_cachebust`` configuration value to a true value. -.. _custom_cache_busters: - Customizing the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``cachebust`` option to -:meth:`~pyramid.config.Configurator.add_static_view` may be set to any object -that implements the interface :class:`~pyramid.interfaces.ICacheBuster`. +Revisiting from the previous section: + +.. code-block:: python + :linenos: + + # config is an instance of pyramid.config.Configurator + config.add_static_view(name='static', path='mypackage:folder/static', + cachebust=True) + +Setting ``cachebust`` to ``True`` instructs :app:`Pyramid` to use a default +cache busting implementation that should work for many situations. The +``cachebust`` may be set to any object that implements the interface +:class:`~pyramid.interfaces.ICacheBuster`. The above configuration is exactly +equivalent to: + +.. code-block:: python + :linenos: -:app:`Pyramid` ships with a very simplistic + from pyramid.static import PathSegmentMd5CacheBuster + + # config is an instance of pyramid.config.Configurator + config.add_static_view(name='static', path='mypackage:folder/static', + cachebust=PathSegmentMd5CacheBuster()) + +:app:`Pyramid` includes a handful of ready to use cache buster implementations: +:class:`~pyramid.static.PathSegmentMd5CacheBuster`, which inserts an md5 +checksum token in the path portion of the asset's URL, +:class:`~pyramid.static.QueryStringMd5CacheBuster`, which adds an md5 checksum +token to the query string of the asset's URL, and :class:`~pyramid.static.QueryStringConstantCacheBuster`, which adds an -arbitrary token you provide to the query string of the asset's URL. This -is almost never what you want in production as it does not allow fine-grained -busting of individual assets. +arbitrary token you provide to the query string of the asset's URL. In order to implement your own cache buster, you can write your own class from scratch which implements the :class:`~pyramid.interfaces.ICacheBuster` interface. Alternatively you may choose to subclass one of the existing implementations. One of the most likely scenarios is you'd want to change the -way the asset token is generated. To do this just subclass +way the asset token is generated. To do this just subclass either +:class:`~pyramid.static.PathSegmentCacheBuster` or :class:`~pyramid.static.QueryStringCacheBuster` and define a -``tokenize(pathspec)`` method. Here is an example which uses Git to get -the hash of the current commit: +``tokenize(pathspec)`` method. Here is an example which just uses Git to get +the hash of the currently checked out code: .. code-block:: python :linenos: import os import subprocess - from pyramid.static import QueryStringCacheBuster + from pyramid.static import PathSegmentCacheBuster - class GitCacheBuster(QueryStringCacheBuster): + class GitCacheBuster(PathSegmentCacheBuster): """ Assuming your code is installed as a Git checkout, as opposed to an egg from an egg repository like PYPI, you can use this cachebuster to get the current commit's SHA1 to use as the cache bust token. """ - def __init__(self, param='x'): - super(GitCacheBuster, self).__init__(param=param) + def __init__(self): here = os.path.dirname(os.path.abspath(__file__)) self.sha1 = subprocess.check_output( ['git', 'rev-parse', 'HEAD'], @@ -464,60 +476,26 @@ the hash of the current commit: Choosing a Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~ -Many caching HTTP proxies will fail to cache a resource if the URL contains -a query string. Therefore, in general, you should prefer a cache busting -strategy which modifies the path segment rather than methods which add a -token to the query string. - -You will need to consider whether the :app:`Pyramid` application will be -serving your static assets, whether you are using an external asset pipeline -to handle rewriting urls internal to the css/javascript, and how fine-grained -do you want the cache busting tokens to be. - -In many cases you will want to host the static assets on another web server -or externally on a CDN. In these cases your :app:`Pyramid` application may not -even have access to a copy of the static assets. In order to cache bust these -assets you will need some information about them. - -If you are using an external asset pipeline to generate your static files you -should consider using the :class:`~pyramid.static.ManifestCacheBuster`. -This cache buster can load a standard JSON formatted file generated by your -pipeline and use it to cache bust the assets. This has many performance -advantages as :app:`Pyramid` does not need to look at the files to generate -any cache busting tokens, but still supports fine-grained per-file tokens. - -Assuming an example ``manifest.json`` like: - -.. code-block:: json - - { - "css/main.css": "css/main-678b7c80.css", - "images/background.png": "images/background-a8169106.png" - } - -The following code would set up a cachebuster: - -.. code-block:: python - :linenos: - - from pyramid.path import AssetResolver - from pyramid.static import ManifestCacheBuster - - resolver = AssetResolver() - manifest = resolver.resolve('myapp:static/manifest.json') - config.add_static_view( - name='http://mycdn.example.com/', - path='mypackage:static', - cachebust=ManifestCacheBuster(manifest.abspath())) - -A simpler approach is to use the -:class:`~pyramid.static.QueryStringConstantCacheBuster` to generate a global -token that will bust all of the assets at once. The advantage of this strategy -is that it is simple and by using the query string there doesn't need to be -any shared information between your application and the static assets. - -The following code would set up a cachebuster that just uses the time at -start up as a cachebust token: +The default cache buster implementation, +:class:`~pyramid.static.PathSegmentMd5CacheBuster`, works very well assuming +that you're using :app:`Pyramid` to serve your static assets. The md5 checksum +is fine grained enough that browsers should only request new versions of +specific assets that have changed. Many caching HTTP proxies will fail to +cache a resource if the URL contains a query string. In general, therefore, +you should prefer a cache busting strategy which modifies the path segment to a +strategy which adds a query string. + +It is possible, however, that your static assets are being served by another +web server or externally on a CDN. In these cases modifying the path segment +for a static asset URL would cause the external service to fail to find the +asset, causing your customer to get a 404. In these cases you would need to +fall back to a cache buster which adds a query string. It is even possible +that there isn't a copy of your static assets available to the :app:`Pyramid` +application, so a cache busting implementation that generates md5 checksums +would fail since it can't access the assets. In such a case, +:class:`~pyramid.static.QueryStringConstantCacheBuster` is a reasonable +fallback. The following code would set up a cachebuster that just uses the +time at start up as a cachebust token: .. code-block:: python :linenos: @@ -528,7 +506,7 @@ start up as a cachebust token: config.add_static_view( name='http://mycdn.example.com/', path='mypackage:static', - cachebust=QueryStringConstantCacheBuster(str(int(time.time())))) + cachebust=QueryStringConstantCacheBuster(str(time.time()))) .. index:: single: static assets view @@ -540,24 +518,85 @@ Often one needs to refer to images and other static assets inside CSS and JavaScript files. If cache busting is active, the final static asset URL is not available until the static assets have been assembled. These URLs cannot be handwritten. Thus, when having static asset references in CSS and JavaScript, -one needs to perform one of the following tasks: +one needs to perform one of the following tasks. * Process the files by using a precompiler which rewrites URLs to their final - cache busted form. Then, you can use the - :class:`~pyramid.static.ManifestCacheBuster` to synchronize your asset - pipeline with :app:`Pyramid`, allowing the pipeline to have full control - over the final URLs of your assets. + cache busted form. * Templatize JS and CSS, and call ``request.static_url()`` inside their template code. * Pass static URL references to CSS and JavaScript via other means. -If your CSS and JavaScript assets use URLs to reference other assets it is -recommended that you implement an external asset pipeline that can rewrite the -generated static files with new URLs containing cache busting tokens. The -machinery inside :app:`Pyramid` will not help with this step as it has very -little knowledge of the asset types your application may use. +Below are some simple approaches for CSS and JS programming which consider +asset cache busting. These approaches do not require additional tools or +packages. + +Relative cache busted URLs in CSS ++++++++++++++++++++++++++++++++++ + +Consider a CSS file ``/static/theme/css/site.css`` which contains the following +CSS code. + +.. code-block:: css + + body { + background: url(/static/theme/img/background.jpg); + } + +Any changes to ``background.jpg`` would not appear to the visitor because the +URL path is not cache busted as it is. Instead we would have to construct an +URL to the background image with the default ``PathSegmentCacheBuster`` cache +busting mechanism:: + + https://site/static/1eeb262c717/theme/img/background.jpg + +Every time the image is updated, the URL would need to be changed. It is not +practical to write this non-human readable URL into a CSS file. + +However, the CSS file itself is cache busted and is located under the path for +static assets. This lets us use relative references in our CSS to cache bust +the image. + +.. code-block:: css + + body { + background: url(../img/background.jpg); + } + +The browser would interpret this as having the CSS file hash in URL:: + + https://site/static/ab234b262c71/theme/css/../img/background.jpg + +The downside of this approach is that if the background image changes, one +needs to bump the CSS file. The CSS file hash change signals the caches that +the relative URL to the image in the CSS has been changed. When updating CSS +and related image assets, updates usually happen hand in hand, so this does not +add extra effort to theming workflow. + +Passing cache busted URLs to JavaScript ++++++++++++++++++++++++++++++++++++++++ + +For JavaScript, one can pass static asset URLs as function arguments or +globals. The globals can be generated in page template code, having access to +the ``request.static_url()`` function. + +Below is a simple example of passing a cached busted image URL in the Jinja2 +template language. Put the following code into the ```` section of the +relevant page. + +.. code-block:: html + + + +Then in your main ``site.js`` file, put the following code. + +.. code-block:: javascript + + var image = new Image(window.assets.backgroundImage); .. _advanced_static: -- cgit v1.2.3 From 3a41196208c7fd78cfb177bb5105c6a702436b78 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Tue, 20 Oct 2015 00:32:14 -0500 Subject: update cache buster prose and add ManifestCacheBuster redux of #2013 --- docs/api/static.rst | 8 +- docs/glossary.rst | 4 + docs/narr/assets.rst | 257 ++++++++++++++++++++++----------------------------- 3 files changed, 114 insertions(+), 155 deletions(-) (limited to 'docs') diff --git a/docs/api/static.rst b/docs/api/static.rst index b6b279139..f3727e197 100644 --- a/docs/api/static.rst +++ b/docs/api/static.rst @@ -9,17 +9,11 @@ :members: :inherited-members: - .. autoclass:: PathSegmentCacheBuster + .. autoclass:: ManifestCacheBuster :members: .. autoclass:: QueryStringCacheBuster :members: - .. autoclass:: PathSegmentMd5CacheBuster - :members: - - .. autoclass:: QueryStringMd5CacheBuster - :members: - .. autoclass:: QueryStringConstantCacheBuster :members: diff --git a/docs/glossary.rst b/docs/glossary.rst index 9c0ea8598..b4bb36421 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -1089,3 +1089,7 @@ Glossary data in a Redis database. See https://pypi.python.org/pypi/pyramid_redis_sessions for more information. + cache busting + A technique used when serving a cacheable static asset in order to force + a client to query the new version of the asset. See :ref:`cache_busting` + for more information. diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 020794062..d36fa49c0 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -356,14 +356,14 @@ may change, and then you'll want the client to load a new copy of the asset. Under normal circumstances you'd just need to wait for the client's cached copy to expire before they get the new version of the static resource. -A commonly used workaround to this problem is a technique known as "cache -busting". Cache busting schemes generally involve generating a URL for a -static asset that changes when the static asset changes. This way headers can -be sent along with the static asset instructing the client to cache the asset -for a very long time. When a static asset is changed, the URL used to refer to -it in a web page also changes, so the client sees it as a new resource and -requests the asset, regardless of any caching policy set for the resource's old -URL. +A commonly used workaround to this problem is a technique known as +:term:`cache busting`. Cache busting schemes generally involve generating a +URL for a static asset that changes when the static asset changes. This way +headers can be sent along with the static asset instructing the client to cache +the asset for a very long time. When a static asset is changed, the URL used +to refer to it in a web page also changes, so the client sees it as a new +resource and requests the asset, regardless of any caching policy set for the +resource's old URL. :app:`Pyramid` can be configured to produce cache busting URLs for static assets by passing the optional argument, ``cachebust`` to @@ -372,30 +372,38 @@ assets by passing the optional argument, ``cachebust`` to .. code-block:: python :linenos: + import time + from pyramid.static import QueryStringConstantCacheBuster + # config is an instance of pyramid.config.Configurator - config.add_static_view(name='static', path='mypackage:folder/static', - cachebust=True) + config.add_static_view( + name='static', path='mypackage:folder/static', + cachebust=QueryStringConstantCacheBuster(str(int(time.time()))), + ) Setting the ``cachebust`` argument instructs :app:`Pyramid` to use a cache -busting scheme which adds the md5 checksum for a static asset as a path segment -in the asset's URL: +busting scheme which adds the curent time for a static asset to the query +string in the asset's URL: .. code-block:: python :linenos: js_url = request.static_url('mypackage:folder/static/js/myapp.js') - # Returns: 'http://www.example.com/static/c9658b3c0a314a1ca21e5988e662a09e/js/myapp.js' + # Returns: 'http://www.example.com/static/js/myapp.js?x=1445318121' -When the asset changes, so will its md5 checksum, and therefore so will its -URL. Supplying the ``cachebust`` argument also causes the static view to set -headers instructing clients to cache the asset for ten years, unless the -``cache_max_age`` argument is also passed, in which case that value is used. +When the web server restarts, the time constant will change and therefore so +will its URL. Supplying the ``cachebust`` argument also causes the static +view to set headers instructing clients to cache the asset for ten years, +unless the ``cache_max_age`` argument is also passed, in which case that +value is used. .. note:: - md5 checksums are cached in RAM, so if you change a static resource without - restarting your application, you may still generate URLs with a stale md5 - checksum. + Cache busting is an inherently complex topic as it integrates the asset + pipeline and the web application. It is expected and desired that + application authors will write their own cache buster implementations + conforming to the properties of their own asset pipelines. See + :ref:`custom_cache_busters` for information on writing your own. Disabling the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -406,65 +414,45 @@ configured cache busters without changing calls to ``PYRAMID_PREVENT_CACHEBUST`` environment variable or the ``pyramid.prevent_cachebust`` configuration value to a true value. +.. _custom_cache_busters: + Customizing the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Revisiting from the previous section: - -.. code-block:: python - :linenos: - - # config is an instance of pyramid.config.Configurator - config.add_static_view(name='static', path='mypackage:folder/static', - cachebust=True) - -Setting ``cachebust`` to ``True`` instructs :app:`Pyramid` to use a default -cache busting implementation that should work for many situations. The -``cachebust`` may be set to any object that implements the interface -:class:`~pyramid.interfaces.ICacheBuster`. The above configuration is exactly -equivalent to: - -.. code-block:: python - :linenos: +The ``cachebust`` option to +:meth:`~pyramid.config.Configurator.add_static_view` may be set to any object +that implements the interface :class:`~pyramid.interfaces.ICacheBuster`. - from pyramid.static import PathSegmentMd5CacheBuster - - # config is an instance of pyramid.config.Configurator - config.add_static_view(name='static', path='mypackage:folder/static', - cachebust=PathSegmentMd5CacheBuster()) - -:app:`Pyramid` includes a handful of ready to use cache buster implementations: -:class:`~pyramid.static.PathSegmentMd5CacheBuster`, which inserts an md5 -checksum token in the path portion of the asset's URL, -:class:`~pyramid.static.QueryStringMd5CacheBuster`, which adds an md5 checksum -token to the query string of the asset's URL, and +:app:`Pyramid` ships with a very simplistic :class:`~pyramid.static.QueryStringConstantCacheBuster`, which adds an -arbitrary token you provide to the query string of the asset's URL. +arbitrary token you provide to the query string of the asset's URL. This +is almost never what you want in production as it does not allow fine-grained +busting of individual assets. In order to implement your own cache buster, you can write your own class from scratch which implements the :class:`~pyramid.interfaces.ICacheBuster` interface. Alternatively you may choose to subclass one of the existing implementations. One of the most likely scenarios is you'd want to change the -way the asset token is generated. To do this just subclass either -:class:`~pyramid.static.PathSegmentCacheBuster` or +way the asset token is generated. To do this just subclass :class:`~pyramid.static.QueryStringCacheBuster` and define a -``tokenize(pathspec)`` method. Here is an example which just uses Git to get -the hash of the currently checked out code: +``tokenize(pathspec)`` method. Here is an example which uses Git to get +the hash of the current commit: .. code-block:: python :linenos: import os import subprocess - from pyramid.static import PathSegmentCacheBuster + from pyramid.static import QueryStringCacheBuster - class GitCacheBuster(PathSegmentCacheBuster): + class GitCacheBuster(QueryStringCacheBuster): """ Assuming your code is installed as a Git checkout, as opposed to an egg from an egg repository like PYPI, you can use this cachebuster to get the current commit's SHA1 to use as the cache bust token. """ - def __init__(self): + def __init__(self, param='x'): + super(GitCacheBuster, self).__init__(param=param) here = os.path.dirname(os.path.abspath(__file__)) self.sha1 = subprocess.check_output( ['git', 'rev-parse', 'HEAD'], @@ -476,26 +464,60 @@ the hash of the currently checked out code: Choosing a Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~ -The default cache buster implementation, -:class:`~pyramid.static.PathSegmentMd5CacheBuster`, works very well assuming -that you're using :app:`Pyramid` to serve your static assets. The md5 checksum -is fine grained enough that browsers should only request new versions of -specific assets that have changed. Many caching HTTP proxies will fail to -cache a resource if the URL contains a query string. In general, therefore, -you should prefer a cache busting strategy which modifies the path segment to a -strategy which adds a query string. - -It is possible, however, that your static assets are being served by another -web server or externally on a CDN. In these cases modifying the path segment -for a static asset URL would cause the external service to fail to find the -asset, causing your customer to get a 404. In these cases you would need to -fall back to a cache buster which adds a query string. It is even possible -that there isn't a copy of your static assets available to the :app:`Pyramid` -application, so a cache busting implementation that generates md5 checksums -would fail since it can't access the assets. In such a case, -:class:`~pyramid.static.QueryStringConstantCacheBuster` is a reasonable -fallback. The following code would set up a cachebuster that just uses the -time at start up as a cachebust token: +Many caching HTTP proxies will fail to cache a resource if the URL contains +a query string. Therefore, in general, you should prefer a cache busting +strategy which modifies the path segment rather than methods which add a +token to the query string. + +You will need to consider whether the :app:`Pyramid` application will be +serving your static assets, whether you are using an external asset pipeline +to handle rewriting urls internal to the css/javascript, and how fine-grained +do you want the cache busting tokens to be. + +In many cases you will want to host the static assets on another web server +or externally on a CDN. In these cases your :app:`Pyramid` application may not +even have access to a copy of the static assets. In order to cache bust these +assets you will need some information about them. + +If you are using an external asset pipeline to generate your static files you +should consider using the :class:`~pyramid.static.ManifestCacheBuster`. +This cache buster can load a standard JSON formatted file generated by your +pipeline and use it to cache bust the assets. This has many performance +advantages as :app:`Pyramid` does not need to look at the files to generate +any cache busting tokens, but still supports fine-grained per-file tokens. + +Assuming an example ``manifest.json`` like: + +.. code-block:: json + + { + "css/main.css": "css/main-678b7c80.css", + "images/background.png": "images/background-a8169106.png" + } + +The following code would set up a cachebuster: + +.. code-block:: python + :linenos: + + from pyramid.path import AssetResolver + from pyramid.static import ManifestCacheBuster + + resolver = AssetResolver() + manifest = resolver.resolve('myapp:static/manifest.json') + config.add_static_view( + name='http://mycdn.example.com/', + path='mypackage:static', + cachebust=ManifestCacheBuster(manifest.abspath())) + +A simpler approach is to use the +:class:`~pyramid.static.QueryStringConstantCacheBuster` to generate a global +token that will bust all of the assets at once. The advantage of this strategy +is that it is simple and by using the query string there doesn't need to be +any shared information between your application and the static assets. + +The following code would set up a cachebuster that just uses the time at +start up as a cachebust token: .. code-block:: python :linenos: @@ -506,7 +528,7 @@ time at start up as a cachebust token: config.add_static_view( name='http://mycdn.example.com/', path='mypackage:static', - cachebust=QueryStringConstantCacheBuster(str(time.time()))) + cachebust=QueryStringConstantCacheBuster(str(int(time.time())))) .. index:: single: static assets view @@ -518,85 +540,24 @@ Often one needs to refer to images and other static assets inside CSS and JavaScript files. If cache busting is active, the final static asset URL is not available until the static assets have been assembled. These URLs cannot be handwritten. Thus, when having static asset references in CSS and JavaScript, -one needs to perform one of the following tasks. +one needs to perform one of the following tasks: * Process the files by using a precompiler which rewrites URLs to their final - cache busted form. + cache busted form. Then, you can use the + :class:`~pyramid.static.ManifestCacheBuster` to synchronize your asset + pipeline with :app:`Pyramid`, allowing the pipeline to have full control + over the final URLs of your assets. * Templatize JS and CSS, and call ``request.static_url()`` inside their template code. * Pass static URL references to CSS and JavaScript via other means. -Below are some simple approaches for CSS and JS programming which consider -asset cache busting. These approaches do not require additional tools or -packages. - -Relative cache busted URLs in CSS -+++++++++++++++++++++++++++++++++ - -Consider a CSS file ``/static/theme/css/site.css`` which contains the following -CSS code. - -.. code-block:: css - - body { - background: url(/static/theme/img/background.jpg); - } - -Any changes to ``background.jpg`` would not appear to the visitor because the -URL path is not cache busted as it is. Instead we would have to construct an -URL to the background image with the default ``PathSegmentCacheBuster`` cache -busting mechanism:: - - https://site/static/1eeb262c717/theme/img/background.jpg - -Every time the image is updated, the URL would need to be changed. It is not -practical to write this non-human readable URL into a CSS file. - -However, the CSS file itself is cache busted and is located under the path for -static assets. This lets us use relative references in our CSS to cache bust -the image. - -.. code-block:: css - - body { - background: url(../img/background.jpg); - } - -The browser would interpret this as having the CSS file hash in URL:: - - https://site/static/ab234b262c71/theme/css/../img/background.jpg - -The downside of this approach is that if the background image changes, one -needs to bump the CSS file. The CSS file hash change signals the caches that -the relative URL to the image in the CSS has been changed. When updating CSS -and related image assets, updates usually happen hand in hand, so this does not -add extra effort to theming workflow. - -Passing cache busted URLs to JavaScript -+++++++++++++++++++++++++++++++++++++++ - -For JavaScript, one can pass static asset URLs as function arguments or -globals. The globals can be generated in page template code, having access to -the ``request.static_url()`` function. - -Below is a simple example of passing a cached busted image URL in the Jinja2 -template language. Put the following code into the ```` section of the -relevant page. - -.. code-block:: html - - - -Then in your main ``site.js`` file, put the following code. - -.. code-block:: javascript - - var image = new Image(window.assets.backgroundImage); +If your CSS and JavaScript assets use URLs to reference other assets it is +recommended that you implement an external asset pipeline that can rewrite the +generated static files with new URLs containing cache busting tokens. The +machinery inside :app:`Pyramid` will not help with this step as it has very +little knowledge of the asset types your application may use. .. _advanced_static: -- cgit v1.2.3 From 63163f7bd71fba313bdab162201cb00a8dcc7c9b Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 13 Nov 2015 13:31:40 -0800 Subject: minor grammar, .rst syntax, rewrap 79 cols --- docs/narr/upgrading.rst | 163 +++++++++++++++++++++++------------------------- 1 file changed, 79 insertions(+), 84 deletions(-) (limited to 'docs') diff --git a/docs/narr/upgrading.rst b/docs/narr/upgrading.rst index eb3194a65..db9b5e090 100644 --- a/docs/narr/upgrading.rst +++ b/docs/narr/upgrading.rst @@ -12,26 +12,26 @@ applications keep working when you upgrade the Pyramid version you're using. .. sidebar:: About Release Numbering Conventionally, application version numbering in Python is described as - ``major.minor.micro``. If your Pyramid version is "1.2.3", it means - you're running a version of Pyramid with the major version "1", the minor - version "2" and the micro version "3". A "major" release is one that - increments the first-dot number; 2.X.X might follow 1.X.X. A "minor" - release is one that increments the second-dot number; 1.3.X might follow - 1.2.X. A "micro" release is one that increments the third-dot number; - 1.2.3 might follow 1.2.2. In general, micro releases are "bugfix-only", - and contain no new features, minor releases contain new features but are - largely backwards compatible with older versions, and a major release - indicates a large set of backwards incompatibilities. + ``major.minor.micro``. If your Pyramid version is "1.2.3", it means you're + running a version of Pyramid with the major version "1", the minor version + "2" and the micro version "3". A "major" release is one that increments the + first-dot number; 2.X.X might follow 1.X.X. A "minor" release is one that + increments the second-dot number; 1.3.X might follow 1.2.X. A "micro" + release is one that increments the third-dot number; 1.2.3 might follow + 1.2.2. In general, micro releases are "bugfix-only", and contain no new + features, minor releases contain new features but are largely backwards + compatible with older versions, and a major release indicates a large set of + backwards incompatibilities. The Pyramid core team is conservative when it comes to removing features. We -don't remove features unnecessarily, but we're human, and we make mistakes -which cause some features to be evolutionary dead ends. Though we are -willing to support dead-end features for some amount of time, some eventually -have to be removed when the cost of supporting them outweighs the benefit of -keeping them around, because each feature in Pyramid represents a certain -documentation and maintenance burden. - -Deprecation and Removal Policy +don't remove features unnecessarily, but we're human and we make mistakes which +cause some features to be evolutionary dead ends. Though we are willing to +support dead-end features for some amount of time, some eventually have to be +removed when the cost of supporting them outweighs the benefit of keeping them +around, because each feature in Pyramid represents a certain documentation and +maintenance burden. + +Deprecation and removal policy ------------------------------ When a feature is scheduled for removal from Pyramid or any of its official @@ -51,50 +51,49 @@ When a deprecated feature is eventually removed: - A note is added to the :ref:`changelog` about the removal. -Features are never removed in *micro* releases. They are only removed in -minor and major releases. Deprecated features are kept around for at least -*three* minor releases from the time the feature became deprecated. -Therefore, if a feature is added in Pyramid 1.0, but it's deprecated in -Pyramid 1.1, it will be kept around through all 1.1.X releases, all 1.2.X -releases and all 1.3.X releases. It will finally be removed in the first -1.4.X release. - -Sometimes features are "docs-deprecated" instead of formally deprecated. -This means that the feature will be kept around indefinitely, but it will be -removed from the documentation or a note will be added to the documentation -telling folks to use some other newer feature. This happens when the cost of -keeping an old feature around is very minimal and the support and -documentation burden is very low. For example, we might rename a function -that is an API without changing the arguments it accepts. In this case, -we'll often rename the function, and change the docs to point at the new -function name, but leave around a backwards compatibility alias to the old -function name so older code doesn't break. +Features are never removed in *micro* releases. They are only removed in minor +and major releases. Deprecated features are kept around for at least *three* +minor releases from the time the feature became deprecated. Therefore, if a +feature is added in Pyramid 1.0, but it's deprecated in Pyramid 1.1, it will be +kept around through all 1.1.X releases, all 1.2.X releases and all 1.3.X +releases. It will finally be removed in the first 1.4.X release. + +Sometimes features are "docs-deprecated" instead of formally deprecated. This +means that the feature will be kept around indefinitely, but it will be removed +from the documentation or a note will be added to the documentation telling +folks to use some other newer feature. This happens when the cost of keeping +an old feature around is very minimal and the support and documentation burden +is very low. For example, we might rename a function that is an API without +changing the arguments it accepts. In this case, we'll often rename the +function, and change the docs to point at the new function name, but leave +around a backwards compatibility alias to the old function name so older code +doesn't break. "Docs deprecated" features tend to work "forever", meaning that they won't be removed, and they'll never generate a deprecation warning. However, such changes are noted in the :ref:`changelog`, so it's possible to know that you -should change older spellings to newer ones to ensure that people reading -your code can find the APIs you're using in the Pyramid docs. +should change older spellings to newer ones to ensure that people reading your +code can find the APIs you're using in the Pyramid docs. -Consulting the Change History +Consulting the change history ----------------------------- -Your first line of defense against application failures caused by upgrading -to a newer Pyramid release is always to read the :ref:`changelog`. to find -the deprecations and removals for each release between the release you're -currently running and the one you wish to upgrade to. The change history -notes every deprecation within a ``Deprecation`` section and every removal -within a ``Backwards Incompatibilies`` section for each release. +Your first line of defense against application failures caused by upgrading to +a newer Pyramid release is always to read the :ref:`changelog` to find the +deprecations and removals for each release between the release you're currently +running and the one to which you wish to upgrade. The change history notes +every deprecation within a ``Deprecation`` section and every removal within a +``Backwards Incompatibilies`` section for each release. -The change history often contains instructions for changing your code to -avoid deprecation warnings and how to change docs-deprecated spellings to -newer ones. You can follow along with each deprecation explanation in the -change history, simply doing a grep or other code search to your application, -using the change log examples to remediate each potential problem. +The change history often contains instructions for changing your code to avoid +deprecation warnings and how to change docs-deprecated spellings to newer ones. +You can follow along with each deprecation explanation in the change history, +simply doing a grep or other code search to your application, using the change +log examples to remediate each potential problem. .. _testing_under_new_release: -Testing Your Application Under a New Pyramid Release +Testing your application under a new Pyramid release ---------------------------------------------------- Once you've upgraded your application to a new Pyramid release and you've @@ -106,25 +105,24 @@ you can see DeprecationWarnings printed to the console when the tests run. $ python -Wd setup.py test -q -The ``-Wd`` argument is an argument that tells Python to print deprecation -warnings to the console. Note that the ``-Wd`` flag is only required for -Python 2.7 and better: Python versions 2.6 and older print deprecation -warnings to the console by default. See `the Python -W flag documentation -`_ for more -information. +The ``-Wd`` argument tells Python to print deprecation warnings to the console. +Note that the ``-Wd`` flag is only required for Python 2.7 and better: Python +versions 2.6 and older print deprecation warnings to the console by default. +See `the Python -W flag documentation +`_ for more information. As your tests run, deprecation warnings will be printed to the console -explaining the deprecation and providing instructions about how to prevent -the deprecation warning from being issued. For example: +explaining the deprecation and providing instructions about how to prevent the +deprecation warning from being issued. For example: -.. code-block:: text +.. code-block:: bash $ python -Wd setup.py test -q # .. elided ... running build_ext - /home/chrism/projects/pyramid/env27/myproj/myproj/views.py:3: - DeprecationWarning: static: The "pyramid.view.static" class is deprecated - as of Pyramid 1.1; use the "pyramid.static.static_view" class instead with + /home/chrism/projects/pyramid/env27/myproj/myproj/views.py:3: + DeprecationWarning: static: The "pyramid.view.static" class is deprecated + as of Pyramid 1.1; use the "pyramid.static.static_view" class instead with the "use_subpath" argument set to True. from pyramid.view import static . @@ -144,8 +142,8 @@ pyramid.view import static``) that is causing the problem: from pyramid.view import static myview = static('static', 'static') -The deprecation warning tells me how to fix it, so I can change the code to -do things the newer way: +The deprecation warning tells me how to fix it, so I can change the code to do +things the newer way: .. code-block:: python :linenos: @@ -155,10 +153,10 @@ do things the newer way: from pyramid.static import static_view myview = static_view('static', 'static', use_subpath=True) -When I run the tests again, the deprecation warning is no longer printed to -my console: +When I run the tests again, the deprecation warning is no longer printed to my +console: -.. code-block:: text +.. code-block:: bash $ python -Wd setup.py test -q # .. elided ... @@ -170,7 +168,7 @@ my console: OK -My Application Doesn't Have Any Tests or Has Few Tests +My application doesn't have any tests or has few tests ------------------------------------------------------ If your application has no tests, or has only moderate test coverage, running @@ -178,8 +176,8 @@ tests won't tell you very much, because the Pyramid codepaths that generate deprecation warnings won't be executed. In this circumstance, you can start your application interactively under a -server run with the ``PYTHONWARNINGS`` environment variable set to -``default``. On UNIX, you can do that via: +server run with the ``PYTHONWARNINGS`` environment variable set to ``default``. +On UNIX, you can do that via: .. code-block:: bash @@ -194,16 +192,15 @@ On Windows, you need to issue two commands: At this point, it's ensured that deprecation warnings will be printed to the console whenever a codepath is hit that generates one. You can then click -around in your application interactively to try to generate them, and -remediate as explained in :ref:`testing_under_new_release`. +around in your application interactively to try to generate them, and remediate +as explained in :ref:`testing_under_new_release`. See `the PYTHONWARNINGS environment variable documentation `_ or `the Python -W flag documentation -`_ for more -information. +`_ for more information. -Upgrading to the Very Latest Pyramid Release +Upgrading to the very latest Pyramid release -------------------------------------------- When you upgrade your application to the most recent Pyramid release, @@ -220,15 +217,13 @@ advisable to do this: :ref:`testing_under_new_release`. Note any deprecation warnings and remediate. -- Upgrade to the most recent 1.3 release, 1.3.3. Run your application's - tests, note any deprecation warnings and remediate. +- Upgrade to the most recent 1.3 release, 1.3.3. Run your application's tests, + note any deprecation warnings, and remediate. - Upgrade to 1.4.4. Run your application's tests, note any deprecation - warnings and remediate. + warnings, and remediate. If you skip testing your application under each minor release (for example if -you upgrade directly from 1.2.1 to 1.4.4), you might miss a deprecation -warning and waste more time trying to figure out an error caused by a feature -removal than it would take to upgrade stepwise through each minor release. - - +you upgrade directly from 1.2.1 to 1.4.4), you might miss a deprecation warning +and waste more time trying to figure out an error caused by a feature removal +than it would take to upgrade stepwise through each minor release. -- cgit v1.2.3 From bdc3f28699c5fc6b127a1aa502b8372b149429f2 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 15 Nov 2015 05:46:47 -0800 Subject: minor grammar, .rst syntax fixes, rewrap 79 cols --- docs/narr/threadlocals.rst | 226 +++++++++++++++++++++------------------------ 1 file changed, 106 insertions(+), 120 deletions(-) (limited to 'docs') diff --git a/docs/narr/threadlocals.rst b/docs/narr/threadlocals.rst index afe56de3e..7437a3a76 100644 --- a/docs/narr/threadlocals.rst +++ b/docs/narr/threadlocals.rst @@ -8,26 +8,24 @@ Thread Locals ============= -A :term:`thread local` variable is a variable that appears to be a -"global" variable to an application which uses it. However, unlike a -true global variable, one thread or process serving the application -may receive a different value than another thread or process when that -variable is "thread local". +A :term:`thread local` variable is a variable that appears to be a "global" +variable to an application which uses it. However, unlike a true global +variable, one thread or process serving the application may receive a different +value than another thread or process when that variable is "thread local". -When a request is processed, :app:`Pyramid` makes two :term:`thread -local` variables available to the application: a "registry" and a -"request". +When a request is processed, :app:`Pyramid` makes two :term:`thread local` +variables available to the application: a "registry" and a "request". Why and How :app:`Pyramid` Uses Thread Local Variables ---------------------------------------------------------- +------------------------------------------------------ -How are thread locals beneficial to :app:`Pyramid` and application -developers who use :app:`Pyramid`? Well, usually they're decidedly -**not**. Using a global or a thread local variable in any application -usually makes it a lot harder to understand for a casual reader. Use -of a thread local or a global is usually just a way to avoid passing -some value around between functions, which is itself usually a very -bad idea, at least if code readability counts as an important concern. +How are thread locals beneficial to :app:`Pyramid` and application developers +who use :app:`Pyramid`? Well, usually they're decidedly **not**. Using a +global or a thread local variable in any application usually makes it a lot +harder to understand for a casual reader. Use of a thread local or a global is +usually just a way to avoid passing some value around between functions, which +is itself usually a very bad idea, at least if code readability counts as an +important concern. For historical reasons, however, thread local variables are indeed consulted by various :app:`Pyramid` API functions. For example, the implementation of the @@ -40,119 +38,107 @@ application registry, from which it looks up the authentication policy; it then uses the authentication policy to retrieve the authenticated user id. This is how :app:`Pyramid` allows arbitrary authentication policies to be "plugged in". -When they need to do so, :app:`Pyramid` internals use two API -functions to retrieve the :term:`request` and :term:`application -registry`: :func:`~pyramid.threadlocal.get_current_request` and -:func:`~pyramid.threadlocal.get_current_registry`. The former -returns the "current" request; the latter returns the "current" -registry. Both ``get_current_*`` functions retrieve an object from a -thread-local data structure. These API functions are documented in -:ref:`threadlocal_module`. - -These values are thread locals rather than true globals because one -Python process may be handling multiple simultaneous requests or even -multiple :app:`Pyramid` applications. If they were true globals, -:app:`Pyramid` could not handle multiple simultaneous requests or -allow more than one :app:`Pyramid` application instance to exist in -a single Python process. - -Because one :app:`Pyramid` application is permitted to call -*another* :app:`Pyramid` application from its own :term:`view` code -(perhaps as a :term:`WSGI` app with help from the -:func:`pyramid.wsgi.wsgiapp2` decorator), these variables are -managed in a *stack* during normal system operations. The stack -instance itself is a :class:`threading.local`. +When they need to do so, :app:`Pyramid` internals use two API functions to +retrieve the :term:`request` and :term:`application registry`: +:func:`~pyramid.threadlocal.get_current_request` and +:func:`~pyramid.threadlocal.get_current_registry`. The former returns the +"current" request; the latter returns the "current" registry. Both +``get_current_*`` functions retrieve an object from a thread-local data +structure. These API functions are documented in :ref:`threadlocal_module`. + +These values are thread locals rather than true globals because one Python +process may be handling multiple simultaneous requests or even multiple +:app:`Pyramid` applications. If they were true globals, :app:`Pyramid` could +not handle multiple simultaneous requests or allow more than one :app:`Pyramid` +application instance to exist in a single Python process. + +Because one :app:`Pyramid` application is permitted to call *another* +:app:`Pyramid` application from its own :term:`view` code (perhaps as a +:term:`WSGI` app with help from the :func:`pyramid.wsgi.wsgiapp2` decorator), +these variables are managed in a *stack* during normal system operations. The +stack instance itself is a :class:`threading.local`. During normal operations, the thread locals stack is managed by a -:term:`Router` object. At the beginning of a request, the Router -pushes the application's registry and the request on to the stack. At -the end of a request, the stack is popped. The topmost request and -registry on the stack are considered "current". Therefore, when the -system is operating normally, the very definition of "current" is -defined entirely by the behavior of a pyramid :term:`Router`. +:term:`Router` object. At the beginning of a request, the Router pushes the +application's registry and the request on to the stack. At the end of a +request, the stack is popped. The topmost request and registry on the stack +are considered "current". Therefore, when the system is operating normally, +the very definition of "current" is defined entirely by the behavior of a +pyramid :term:`Router`. However, during unit testing, no Router code is ever invoked, and the -definition of "current" is defined by the boundary between calls to -the :meth:`pyramid.config.Configurator.begin` and -:meth:`pyramid.config.Configurator.end` methods (or between -calls to the :func:`pyramid.testing.setUp` and -:func:`pyramid.testing.tearDown` functions). These functions push -and pop the threadlocal stack when the system is under test. See -:ref:`test_setup_and_teardown` for the definitions of these functions. - -Scripts which use :app:`Pyramid` machinery but never actually start -a WSGI server or receive requests via HTTP such as scripts which use -the :mod:`pyramid.scripting` API will never cause any Router code -to be executed. However, the :mod:`pyramid.scripting` APIs also -push some values on to the thread locals stack as a matter of course. -Such scripts should expect the -:func:`~pyramid.threadlocal.get_current_request` function to always -return ``None``, and should expect the -:func:`~pyramid.threadlocal.get_current_registry` function to return -exactly the same :term:`application registry` for every request. +definition of "current" is defined by the boundary between calls to the +:meth:`pyramid.config.Configurator.begin` and +:meth:`pyramid.config.Configurator.end` methods (or between calls to the +:func:`pyramid.testing.setUp` and :func:`pyramid.testing.tearDown` functions). +These functions push and pop the threadlocal stack when the system is under +test. See :ref:`test_setup_and_teardown` for the definitions of these +functions. + +Scripts which use :app:`Pyramid` machinery but never actually start a WSGI +server or receive requests via HTTP, such as scripts which use the +:mod:`pyramid.scripting` API, will never cause any Router code to be executed. +However, the :mod:`pyramid.scripting` APIs also push some values on to the +thread locals stack as a matter of course. Such scripts should expect the +:func:`~pyramid.threadlocal.get_current_request` function to always return +``None``, and should expect the +:func:`~pyramid.threadlocal.get_current_registry` function to return exactly +the same :term:`application registry` for every request. Why You Shouldn't Abuse Thread Locals ------------------------------------- You probably should almost never use the :func:`~pyramid.threadlocal.get_current_request` or -:func:`~pyramid.threadlocal.get_current_registry` functions, except -perhaps in tests. In particular, it's almost always a mistake to use -``get_current_request`` or ``get_current_registry`` in application -code because its usage makes it possible to write code that can be -neither easily tested nor scripted. Inappropriate usage is defined as -follows: +:func:`~pyramid.threadlocal.get_current_registry` functions, except perhaps in +tests. In particular, it's almost always a mistake to use +``get_current_request`` or ``get_current_registry`` in application code because +its usage makes it possible to write code that can be neither easily tested nor +scripted. Inappropriate usage is defined as follows: - ``get_current_request`` should never be called within the body of a - :term:`view callable`, or within code called by a view callable. - View callables already have access to the request (it's passed in to - each as ``request``). - -- ``get_current_request`` should never be called in :term:`resource` code. - If a resource needs access to the request, it should be passed the request - by a :term:`view callable`. - -- ``get_current_request`` function should never be called because it's - "easier" or "more elegant" to think about calling it than to pass a - request through a series of function calls when creating some API - design. Your application should instead almost certainly pass data - derived from the request around rather than relying on being able to - call this function to obtain the request in places that actually - have no business knowing about it. Parameters are *meant* to be - passed around as function arguments, this is why they exist. Don't - try to "save typing" or create "nicer APIs" by using this function - in the place where a request is required; this will only lead to - sadness later. - -- Neither ``get_current_request`` nor ``get_current_registry`` should - ever be called within application-specific forks of third-party - library code. The library you've forked almost certainly has - nothing to do with :app:`Pyramid`, and making it dependent on - :app:`Pyramid` (rather than making your :app:`pyramid` - application depend upon it) means you're forming a dependency in the - wrong direction. - -Use of the :func:`~pyramid.threadlocal.get_current_request` function -in application code *is* still useful in very limited circumstances. -As a rule of thumb, usage of ``get_current_request`` is useful -**within code which is meant to eventually be removed**. For -instance, you may find yourself wanting to deprecate some API that -expects to be passed a request object in favor of one that does not -expect to be passed a request object. But you need to keep -implementations of the old API working for some period of time while -you deprecate the older API. So you write a "facade" implementation -of the new API which calls into the code which implements the older -API. Since the new API does not require the request, your facade -implementation doesn't have local access to the request when it needs -to pass it into the older API implementation. After some period of -time, the older implementation code is disused and the hack that uses -``get_current_request`` is removed. This would be an appropriate -place to use the ``get_current_request``. - -Use of the :func:`~pyramid.threadlocal.get_current_registry` -function should be limited to testing scenarios. The registry made -current by use of the -:meth:`pyramid.config.Configurator.begin` method during a -test (or via :func:`pyramid.testing.setUp`) when you do not pass -one in is available to you via this API. - + :term:`view callable`, or within code called by a view callable. View + callables already have access to the request (it's passed in to each as + ``request``). + +- ``get_current_request`` should never be called in :term:`resource` code. If a + resource needs access to the request, it should be passed the request by a + :term:`view callable`. + +- ``get_current_request`` function should never be called because it's "easier" + or "more elegant" to think about calling it than to pass a request through a + series of function calls when creating some API design. Your application + should instead, almost certainly, pass around data derived from the request + rather than relying on being able to call this function to obtain the request + in places that actually have no business knowing about it. Parameters are + *meant* to be passed around as function arguments; this is why they exist. + Don't try to "save typing" or create "nicer APIs" by using this function in + the place where a request is required; this will only lead to sadness later. + +- Neither ``get_current_request`` nor ``get_current_registry`` should ever be + called within application-specific forks of third-party library code. The + library you've forked almost certainly has nothing to do with :app:`Pyramid`, + and making it dependent on :app:`Pyramid` (rather than making your + :app:`pyramid` application depend upon it) means you're forming a dependency + in the wrong direction. + +Use of the :func:`~pyramid.threadlocal.get_current_request` function in +application code *is* still useful in very limited circumstances. As a rule of +thumb, usage of ``get_current_request`` is useful **within code which is meant +to eventually be removed**. For instance, you may find yourself wanting to +deprecate some API that expects to be passed a request object in favor of one +that does not expect to be passed a request object. But you need to keep +implementations of the old API working for some period of time while you +deprecate the older API. So you write a "facade" implementation of the new API +which calls into the code which implements the older API. Since the new API +does not require the request, your facade implementation doesn't have local +access to the request when it needs to pass it into the older API +implementation. After some period of time, the older implementation code is +disused and the hack that uses ``get_current_request`` is removed. This would +be an appropriate place to use the ``get_current_request``. + +Use of the :func:`~pyramid.threadlocal.get_current_registry` function should be +limited to testing scenarios. The registry made current by use of the +:meth:`pyramid.config.Configurator.begin` method during a test (or via +:func:`pyramid.testing.setUp`) when you do not pass one in is available to you +via this API. -- cgit v1.2.3 From 104870609e23edd1dba4d64869a068e883767552 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sun, 15 Nov 2015 21:59:56 -0600 Subject: update docs to use asset specs with ManifestCacheBuster --- docs/narr/assets.rst | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index d36fa49c0..0f819570c 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -500,15 +500,12 @@ The following code would set up a cachebuster: .. code-block:: python :linenos: - from pyramid.path import AssetResolver from pyramid.static import ManifestCacheBuster - resolver = AssetResolver() - manifest = resolver.resolve('myapp:static/manifest.json') config.add_static_view( name='http://mycdn.example.com/', path='mypackage:static', - cachebust=ManifestCacheBuster(manifest.abspath())) + cachebust=ManifestCacheBuster('myapp:static/manifest.json')) A simpler approach is to use the :class:`~pyramid.static.QueryStringConstantCacheBuster` to generate a global -- cgit v1.2.3 From a3f0a397300aa290ec213760e11f85f40faa1bd7 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 20 Nov 2015 19:21:44 -0800 Subject: use intersphinx links to webob objects --- docs/designdefense.rst | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 1ed4f65a4..ee6d5a317 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -907,23 +907,22 @@ creating a more Zope3-like environment without much effort. .. _http_exception_hierarchy: -Pyramid Uses its Own HTTP Exception Class Hierarchy Rather Than ``webob.exc`` ------------------------------------------------------------------------------ +Pyramid uses its own HTTP exception class hierarchy rather than :mod:`webob.exc` +-------------------------------------------------------------------------------- .. versionadded:: 1.1 The HTTP exception classes defined in :mod:`pyramid.httpexceptions` are very -much like the ones defined in ``webob.exc`` -(e.g. :class:`~pyramid.httpexceptions.HTTPNotFound`, -:class:`~pyramid.httpexceptions.HTTPForbidden`, etc). They have the same -names and largely the same behavior and all have a very similar -implementation, but not the same identity. Here's why they have a separate -identity: +much like the ones defined in :mod:`webob.exc`, (e.g., +:class:`~pyramid.httpexceptions.HTTPNotFound` or +:class:`~pyramid.httpexceptions.HTTPForbidden`). They have the same names and +largely the same behavior, and all have a very similar implementation, but not +the same identity. Here's why they have a separate identity: - Making them separate allows the HTTP exception classes to subclass :class:`pyramid.response.Response`. This speeds up response generation - slightly due to the way the Pyramid router works. The same speedup could - be gained by monkeypatching ``webob.response.Response`` but it's usually + slightly due to the way the Pyramid router works. The same speedup could be + gained by monkeypatching :class:`webob.response.Response`, but it's usually the case that monkeypatching turns out to be evil and wrong. - Making them separate allows them to provide alternate ``__call__`` logic @@ -933,7 +932,7 @@ identity: value of ``RequestClass`` (:class:`pyramid.request.Request`). - Making them separate allows us freedom from having to think about backwards - compatibility code present in ``webob.exc`` having to do with Python 2.4, + compatibility code present in :mod:`webob.exc` having to do with Python 2.4, which we no longer support in Pyramid 1.1+. - We change the behavior of two classes @@ -944,9 +943,9 @@ identity: - Making them separate allows us to influence the docstrings of the exception classes to provide Pyramid-specific documentation. -- Making them separate allows us to silence a stupid deprecation warning - under Python 2.6 when the response objects are used as exceptions (related - to ``self.message``). +- Making them separate allows us to silence a stupid deprecation warning under + Python 2.6 when the response objects are used as exceptions (related to + ``self.message``). .. _simpler_traversal_model: -- cgit v1.2.3 From ee9c620963553a3a959cdfc517f1e0818a21e9c0 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Mon, 23 Nov 2015 12:59:55 -0600 Subject: expose the PickleSerializer --- docs/api/session.rst | 1 + 1 file changed, 1 insertion(+) (limited to 'docs') diff --git a/docs/api/session.rst b/docs/api/session.rst index dde9d20e9..474e2bb32 100644 --- a/docs/api/session.rst +++ b/docs/api/session.rst @@ -17,4 +17,5 @@ .. autofunction:: BaseCookieSessionFactory + .. autoclass:: PickleSerializer -- cgit v1.2.3 From acfdc7085b836045e41568731e5f3223f34d635d Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 4 Dec 2015 02:17:44 -0800 Subject: - add emphasize lines, minor grammar, rewrap 79 columns --- docs/narr/zca.rst | 257 +++++++++++++++++++++++++----------------------------- 1 file changed, 121 insertions(+), 136 deletions(-) (limited to 'docs') diff --git a/docs/narr/zca.rst b/docs/narr/zca.rst index b0e9b1709..784886563 100644 --- a/docs/narr/zca.rst +++ b/docs/narr/zca.rst @@ -9,17 +9,16 @@ .. _zca_chapter: Using the Zope Component Architecture in :app:`Pyramid` -========================================================== +======================================================= -Under the hood, :app:`Pyramid` uses a :term:`Zope Component -Architecture` component registry as its :term:`application registry`. -The Zope Component Architecture is referred to colloquially as the -"ZCA." +Under the hood, :app:`Pyramid` uses a :term:`Zope Component Architecture` +component registry as its :term:`application registry`. The Zope Component +Architecture is referred to colloquially as the "ZCA." The ``zope.component`` API used to access data in a traditional Zope -application can be opaque. For example, here is a typical "unnamed -utility" lookup using the :func:`zope.component.getUtility` global API -as it might appear in a traditional Zope application: +application can be opaque. For example, here is a typical "unnamed utility" +lookup using the :func:`zope.component.getUtility` global API as it might +appear in a traditional Zope application: .. code-block:: python :linenos: @@ -28,23 +27,21 @@ as it might appear in a traditional Zope application: from zope.component import getUtility settings = getUtility(ISettings) -After this code runs, ``settings`` will be a Python dictionary. But -it's unlikely that any "civilian" will be able to figure this out just -by reading the code casually. When the ``zope.component.getUtility`` -API is used by a developer, the conceptual load on a casual reader of -code is high. +After this code runs, ``settings`` will be a Python dictionary. But it's +unlikely that any "civilian" will be able to figure this out just by reading +the code casually. When the ``zope.component.getUtility`` API is used by a +developer, the conceptual load on a casual reader of code is high. -While the ZCA is an excellent tool with which to build a *framework* -such as :app:`Pyramid`, it is not always the best tool with which -to build an *application* due to the opacity of the ``zope.component`` -APIs. Accordingly, :app:`Pyramid` tends to hide the presence of the -ZCA from application developers. You needn't understand the ZCA to -create a :app:`Pyramid` application; its use is effectively only a -framework implementation detail. +While the ZCA is an excellent tool with which to build a *framework* such as +:app:`Pyramid`, it is not always the best tool with which to build an +*application* due to the opacity of the ``zope.component`` APIs. Accordingly, +:app:`Pyramid` tends to hide the presence of the ZCA from application +developers. You needn't understand the ZCA to create a :app:`Pyramid` +application; its use is effectively only a framework implementation detail. -However, developers who are already used to writing :term:`Zope` -applications often still wish to use the ZCA while building a -:app:`Pyramid` application; :app:`Pyramid` makes this possible. +However, developers who are already used to writing :term:`Zope` applications +often still wish to use the ZCA while building a :app:`Pyramid` application. +:app:`Pyramid` makes this possible. .. index:: single: get_current_registry @@ -52,87 +49,81 @@ applications often still wish to use the ZCA while building a single: getSiteManager single: ZCA global API -Using the ZCA Global API in a :app:`Pyramid` Application ------------------------------------------------------------ - -:term:`Zope` uses a single ZCA registry -- the "global" ZCA registry --- for all Zope applications that run in the same Python process, -effectively making it impossible to run more than one Zope application -in a single process. - -However, for ease of deployment, it's often useful to be able to run more -than a single application per process. For example, use of a -:term:`PasteDeploy` "composite" allows you to run separate individual WSGI -applications in the same process, each answering requests for some URL -prefix. This makes it possible to run, for example, a TurboGears application -at ``/turbogears`` and a :app:`Pyramid` application at ``/pyramid``, both -served up using the same :term:`WSGI` server within a single Python process. - -Most production Zope applications are relatively large, making it -impractical due to memory constraints to run more than one Zope -application per Python process. However, a :app:`Pyramid` application -may be very small and consume very little memory, so it's a reasonable -goal to be able to run more than one :app:`Pyramid` application per -process. - -In order to make it possible to run more than one :app:`Pyramid` -application in a single process, :app:`Pyramid` defaults to using a -separate ZCA registry *per application*. - -While this services a reasonable goal, it causes some issues when -trying to use patterns which you might use to build a typical -:term:`Zope` application to build a :app:`Pyramid` application. -Without special help, ZCA "global" APIs such as -:func:`zope.component.getUtility` and :func:`zope.component.getSiteManager` -will use the ZCA "global" registry. Therefore, these APIs -will appear to fail when used in a :app:`Pyramid` application, -because they'll be consulting the ZCA global registry rather than the -component registry associated with your :app:`Pyramid` application. - -There are three ways to fix this: by disusing the ZCA global API -entirely, by using -:meth:`pyramid.config.Configurator.hook_zca` or by passing -the ZCA global registry to the :term:`Configurator` constructor at -startup time. We'll describe all three methods in this section. +Using the ZCA global API in a :app:`Pyramid` application +-------------------------------------------------------- + +:term:`Zope` uses a single ZCA registry—the "global" ZCA registry—for all Zope +applications that run in the same Python process, effectively making it +impossible to run more than one Zope application in a single process. + +However, for ease of deployment, it's often useful to be able to run more than +a single application per process. For example, use of a :term:`PasteDeploy` +"composite" allows you to run separate individual WSGI applications in the same +process, each answering requests for some URL prefix. This makes it possible +to run, for example, a TurboGears application at ``/turbogears`` and a +:app:`Pyramid` application at ``/pyramid``, both served up using the same +:term:`WSGI` server within a single Python process. + +Most production Zope applications are relatively large, making it impractical +due to memory constraints to run more than one Zope application per Python +process. However, a :app:`Pyramid` application may be very small and consume +very little memory, so it's a reasonable goal to be able to run more than one +:app:`Pyramid` application per process. + +In order to make it possible to run more than one :app:`Pyramid` application in +a single process, :app:`Pyramid` defaults to using a separate ZCA registry *per +application*. + +While this services a reasonable goal, it causes some issues when trying to use +patterns which you might use to build a typical :term:`Zope` application to +build a :app:`Pyramid` application. Without special help, ZCA "global" APIs +such as :func:`zope.component.getUtility` and +:func:`zope.component.getSiteManager` will use the ZCA "global" registry. +Therefore, these APIs will appear to fail when used in a :app:`Pyramid` +application, because they'll be consulting the ZCA global registry rather than +the component registry associated with your :app:`Pyramid` application. + +There are three ways to fix this: by disusing the ZCA global API entirely, by +using :meth:`pyramid.config.Configurator.hook_zca` or by passing the ZCA global +registry to the :term:`Configurator` constructor at startup time. We'll +describe all three methods in this section. .. index:: single: request.registry .. _disusing_the_global_zca_api: -Disusing the Global ZCA API +Disusing the global ZCA API +++++++++++++++++++++++++++ ZCA "global" API functions such as ``zope.component.getSiteManager``, ``zope.component.getUtility``, :func:`zope.component.getAdapter`, and :func:`zope.component.getMultiAdapter` aren't strictly necessary. Every -component registry has a method API that offers the same -functionality; it can be used instead. For example, presuming the -``registry`` value below is a Zope Component Architecture component -registry, the following bit of code is equivalent to -``zope.component.getUtility(IFoo)``: +component registry has a method API that offers the same functionality; it can +be used instead. For example, presuming the ``registry`` value below is a Zope +Component Architecture component registry, the following bit of code is +equivalent to ``zope.component.getUtility(IFoo)``: .. code-block:: python registry.getUtility(IFoo) -The full method API is documented in the ``zope.component`` package, -but it largely mirrors the "global" API almost exactly. +The full method API is documented in the ``zope.component`` package, but it +largely mirrors the "global" API almost exactly. -If you are willing to disuse the "global" ZCA APIs and use the method -interface of a registry instead, you need only know how to obtain the -:app:`Pyramid` component registry. +If you are willing to disuse the "global" ZCA APIs and use the method interface +of a registry instead, you need only know how to obtain the :app:`Pyramid` +component registry. There are two ways of doing so: -- use the :func:`pyramid.threadlocal.get_current_registry` - function within :app:`Pyramid` view or resource code. This will - always return the "current" :app:`Pyramid` application registry. +- use the :func:`pyramid.threadlocal.get_current_registry` function within + :app:`Pyramid` view or resource code. This will always return the "current" + :app:`Pyramid` application registry. -- use the attribute of the :term:`request` object named ``registry`` - in your :app:`Pyramid` view code, eg. ``request.registry``. This - is the ZCA component registry related to the running - :app:`Pyramid` application. +- use the attribute of the :term:`request` object named ``registry`` in your + :app:`Pyramid` view code, e.g., ``request.registry``. This is the ZCA + component registry related to the running :app:`Pyramid` application. See :ref:`threadlocals_chapter` for more information about :func:`pyramid.threadlocal.get_current_registry`. @@ -142,7 +133,7 @@ See :ref:`threadlocals_chapter` for more information about .. _hook_zca: -Enabling the ZCA Global API by Using ``hook_zca`` +Enabling the ZCA global API by using ``hook_zca`` +++++++++++++++++++++++++++++++++++++++++++++++++ Consider the following bit of idiomatic :app:`Pyramid` startup code: @@ -157,34 +148,31 @@ Consider the following bit of idiomatic :app:`Pyramid` startup code: config.include('some.other.package') return config.make_wsgi_app() -When the ``app`` function above is run, a :term:`Configurator` is -constructed. When the configurator is created, it creates a *new* -:term:`application registry` (a ZCA component registry). A new -registry is constructed whenever the ``registry`` argument is omitted -when a :term:`Configurator` constructor is called, or when a -``registry`` argument with a value of ``None`` is passed to a -:term:`Configurator` constructor. - -During a request, the application registry created by the Configurator -is "made current". This means calls to -:func:`~pyramid.threadlocal.get_current_registry` in the thread -handling the request will return the component registry associated -with the application. - -As a result, application developers can use ``get_current_registry`` -to get the registry and thus get access to utilities and such, as per -:ref:`disusing_the_global_zca_api`. But they still cannot use the -global ZCA API. Without special treatment, the ZCA global APIs will -always return the global ZCA registry (the one in -``zope.component.globalregistry.base``). - -To "fix" this and make the ZCA global APIs use the "current" -:app:`Pyramid` registry, you need to call -:meth:`~pyramid.config.Configurator.hook_zca` within your setup code. -For example: +When the ``app`` function above is run, a :term:`Configurator` is constructed. +When the configurator is created, it creates a *new* :term:`application +registry` (a ZCA component registry). A new registry is constructed whenever +the ``registry`` argument is omitted, when a :term:`Configurator` constructor +is called, or when a ``registry`` argument with a value of ``None`` is passed +to a :term:`Configurator` constructor. + +During a request, the application registry created by the Configurator is "made +current". This means calls to +:func:`~pyramid.threadlocal.get_current_registry` in the thread handling the +request will return the component registry associated with the application. + +As a result, application developers can use ``get_current_registry`` to get the +registry and thus get access to utilities and such, as per +:ref:`disusing_the_global_zca_api`. But they still cannot use the global ZCA +API. Without special treatment, the ZCA global APIs will always return the +global ZCA registry (the one in ``zope.component.globalregistry.base``). + +To "fix" this and make the ZCA global APIs use the "current" :app:`Pyramid` +registry, you need to call :meth:`~pyramid.config.Configurator.hook_zca` within +your setup code. For example: .. code-block:: python :linenos: + :emphasize-lines: 5 from pyramid.config import Configurator @@ -194,9 +182,9 @@ For example: config.include('some.other.application') return config.make_wsgi_app() -We've added a line to our original startup code, line number 6, which -calls ``config.hook_zca()``. The effect of this line under the hood -is that an analogue of the following code is executed: +We've added a line to our original startup code, line number 5, which calls +``config.hook_zca()``. The effect of this line under the hood is that an +analogue of the following code is executed: .. code-block:: python :linenos: @@ -205,17 +193,15 @@ is that an analogue of the following code is executed: from pyramid.threadlocal import get_current_registry getSiteManager.sethook(get_current_registry) -This causes the ZCA global API to start using the :app:`Pyramid` -application registry in threads which are running a :app:`Pyramid` -request. +This causes the ZCA global API to start using the :app:`Pyramid` application +registry in threads which are running a :app:`Pyramid` request. -Calling ``hook_zca`` is usually sufficient to "fix" the problem of -being able to use the global ZCA API within a :app:`Pyramid` -application. However, it also means that a Zope application that is -running in the same process may start using the :app:`Pyramid` -global registry instead of the Zope global registry, effectively -inverting the original problem. In such a case, follow the steps in -the next section, :ref:`using_the_zca_global_registry`. +Calling ``hook_zca`` is usually sufficient to "fix" the problem of being able +to use the global ZCA API within a :app:`Pyramid` application. However, it +also means that a Zope application that is running in the same process may +start using the :app:`Pyramid` global registry instead of the Zope global +registry, effectively inverting the original problem. In such a case, follow +the steps in the next section, :ref:`using_the_zca_global_registry`. .. index:: single: get_current_registry @@ -224,14 +210,15 @@ the next section, :ref:`using_the_zca_global_registry`. .. _using_the_zca_global_registry: -Enabling the ZCA Global API by Using The ZCA Global Registry +Enabling the ZCA global API by using the ZCA global registry ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -You can tell your :app:`Pyramid` application to use the ZCA global -registry at startup time instead of constructing a new one: +You can tell your :app:`Pyramid` application to use the ZCA global registry at +startup time instead of constructing a new one: .. code-block:: python :linenos: + :emphasize-lines: 5-7 from zope.component import getGlobalSiteManager from pyramid.config import Configurator @@ -243,16 +230,14 @@ registry at startup time instead of constructing a new one: config.include('some.other.application') return config.make_wsgi_app() -Lines 5, 6, and 7 above are the interesting ones. Line 5 retrieves -the global ZCA component registry. Line 6 creates a -:term:`Configurator`, passing the global ZCA registry into its -constructor as the ``registry`` argument. Line 7 "sets up" the global -registry with Pyramid-specific registrations; this is code that is -normally executed when a registry is constructed rather than created, +Lines 5, 6, and 7 above are the interesting ones. Line 5 retrieves the global +ZCA component registry. Line 6 creates a :term:`Configurator`, passing the +global ZCA registry into its constructor as the ``registry`` argument. Line 7 +"sets up" the global registry with Pyramid-specific registrations; this is code +that is normally executed when a registry is constructed rather than created, but we must call it "by hand" when we pass an explicit registry. -At this point, :app:`Pyramid` will use the ZCA global registry -rather than creating a new application-specific registry; since by -default the ZCA global API will use this registry, things will work as -you might expect a Zope app to when you use the global ZCA API. - +At this point, :app:`Pyramid` will use the ZCA global registry rather than +creating a new application-specific registry. Since by default the ZCA global +API will use this registry, things will work as you might expect in a Zope app +when you use the global ZCA API. -- cgit v1.2.3 From a26e3298ddd73ad782132f9b1098e02f7ed55c42 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 4 Dec 2015 02:39:39 -0800 Subject: update references to references to python-distribute.org (see #2141 for discussion) --- docs/narr/project.rst | 4 ++-- docs/narr/scaffolding.rst | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'docs') diff --git a/docs/narr/project.rst b/docs/narr/project.rst index 25f3931e9..ec40bc67c 100644 --- a/docs/narr/project.rst +++ b/docs/narr/project.rst @@ -680,8 +680,8 @@ testing, packaging, and distributing your application. ``setup.py`` is the de facto standard which Python developers use to distribute their reusable code. You can read more about ``setup.py`` files and their usage in the `Setuptools documentation - `_ and `The Hitchhiker's - Guide to Packaging `_. + `_ and `Python Packaging + User Guide `_. Our generated ``setup.py`` looks like this: diff --git a/docs/narr/scaffolding.rst b/docs/narr/scaffolding.rst index 8677359de..164ceb3bf 100644 --- a/docs/narr/scaffolding.rst +++ b/docs/narr/scaffolding.rst @@ -22,10 +22,10 @@ found by the ``pcreate`` command. To create a scaffold template, create a Python :term:`distribution` to house the scaffold which includes a ``setup.py`` that relies on the ``setuptools`` -package. See `Creating a Package -`_ for more information about -how to do this. For example, we'll pretend the distribution you create is -named ``CoolExtension``, and it has a package directory within it named +package. See `Packaging and Distributing Projects +`_ for more information +about how to do this. For example, we'll pretend the distribution you create +is named ``CoolExtension``, and it has a package directory within it named ``coolextension``. Once you've created the distribution, put a "scaffolds" directory within your -- cgit v1.2.3 From d4177a51aff1a46d1c2223db6ed7afd99964e8ad Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 8 Dec 2015 01:41:06 -0800 Subject: update narrative docs and literalinclude source files that use the starter scaffold to reflect its current state --- docs/narr/MyProject/development.ini | 6 +- .../MyProject/myproject/templates/mytemplate.pt | 13 +-- docs/narr/MyProject/myproject/tests.py | 1 + docs/narr/MyProject/production.ini | 2 +- docs/narr/MyProject/setup.py | 45 ++++------- docs/narr/project.rst | 94 ++++++++++++---------- 6 files changed, 81 insertions(+), 80 deletions(-) (limited to 'docs') diff --git a/docs/narr/MyProject/development.ini b/docs/narr/MyProject/development.ini index a9a26e56b..749e574eb 100644 --- a/docs/narr/MyProject/development.ini +++ b/docs/narr/MyProject/development.ini @@ -11,7 +11,7 @@ pyramid.debug_authorization = false pyramid.debug_notfound = false pyramid.debug_routematch = false pyramid.default_locale_name = en -pyramid.includes = +pyramid.includes = pyramid_debugtoolbar # By default, the toolbar only appears for clients from IP addresses @@ -24,7 +24,7 @@ pyramid.includes = [server:main] use = egg:waitress#main -host = 0.0.0.0 +host = 127.0.0.1 port = 6543 ### @@ -57,4 +57,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/narr/MyProject/myproject/templates/mytemplate.pt b/docs/narr/MyProject/myproject/templates/mytemplate.pt index e6b00a145..65d7f0609 100644 --- a/docs/narr/MyProject/myproject/templates/mytemplate.pt +++ b/docs/narr/MyProject/myproject/templates/mytemplate.pt @@ -8,12 +8,12 @@ - Starter Template for The Pyramid Web Framework + Starter Scaffold for The Pyramid Web Framework - + @@ -33,19 +33,20 @@
-

Pyramid starter template

-

Welcome to ${project}, an application generated by
the Pyramid Web Framework.

+

Pyramid Starter scaffold

+

Welcome to ${project}, an application generated by
the Pyramid Web Framework 1.6b2.

diff --git a/docs/narr/MyProject/myproject/tests.py b/docs/narr/MyProject/myproject/tests.py index 8c60407e5..63d00910c 100644 --- a/docs/narr/MyProject/myproject/tests.py +++ b/docs/narr/MyProject/myproject/tests.py @@ -16,6 +16,7 @@ class ViewTests(unittest.TestCase): info = my_view(request) self.assertEqual(info['project'], 'MyProject') + class ViewIntegrationTests(unittest.TestCase): def setUp(self): """ This sets up the application registry with the diff --git a/docs/narr/MyProject/production.ini b/docs/narr/MyProject/production.ini index 9eae9e03f..3ccbe6619 100644 --- a/docs/narr/MyProject/production.ini +++ b/docs/narr/MyProject/production.ini @@ -51,4 +51,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/narr/MyProject/setup.py b/docs/narr/MyProject/setup.py index 9f34540a7..8c019af51 100644 --- a/docs/narr/MyProject/setup.py +++ b/docs/narr/MyProject/setup.py @@ -1,42 +1,30 @@ -"""Setup for the MyProject package. - -""" import os -from setuptools import setup, find_packages - - -HERE = os.path.abspath(os.path.dirname(__file__)) - -with open(os.path.join(HERE, 'README.txt')) as fp: - README = fp.read() - - -with open(os.path.join(HERE, 'CHANGES.txt')) as fp: - CHANGES = fp.read() +from setuptools import setup, find_packages +here = os.path.abspath(os.path.dirname(__file__)) +with open(os.path.join(here, 'README.txt')) as f: + README = f.read() +with open(os.path.join(here, 'CHANGES.txt')) as f: + CHANGES = f.read() -REQUIRES = [ +requires = [ 'pyramid', 'pyramid_chameleon', 'pyramid_debugtoolbar', 'waitress', ] -TESTS_REQUIRE = [ - 'webtest' - ] - setup(name='MyProject', version='0.0', description='MyProject', long_description=README + '\n\n' + CHANGES, classifiers=[ - 'Programming Language :: Python', - 'Framework :: Pyramid', - 'Topic :: Internet :: WWW/HTTP', - 'Topic :: Internet :: WWW/HTTP :: WSGI :: Application', - ], + "Programming Language :: Python", + "Framework :: Pyramid", + "Topic :: Internet :: WWW/HTTP", + "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", + ], author='', author_email='', url='', @@ -44,10 +32,11 @@ setup(name='MyProject', packages=find_packages(), include_package_data=True, zip_safe=False, - install_requires=REQUIRES, - tests_require=TESTS_REQUIRE, - test_suite='myproject', + install_requires=requires, + tests_require=requires, + test_suite="myproject", entry_points="""\ [paste.app_factory] main = myproject:main - """) + """, + ) diff --git a/docs/narr/project.rst b/docs/narr/project.rst index ec40bc67c..4785b60c4 100644 --- a/docs/narr/project.rst +++ b/docs/narr/project.rst @@ -77,7 +77,7 @@ The below example uses the ``pcreate`` command to create a project with the On UNIX: -.. code-block:: text +.. code-block:: bash $ $VENV/bin/pcreate -s starter MyProject @@ -90,7 +90,7 @@ Or on Windows: Here's sample output from a run of ``pcreate`` on UNIX for a project we name ``MyProject``: -.. code-block:: text +.. code-block:: bash $ $VENV/bin/pcreate -s starter MyProject Creating template pyramid @@ -158,7 +158,7 @@ created project directory. On UNIX: -.. code-block:: text +.. code-block:: bash $ cd MyProject $ $VENV/bin/python setup.py develop @@ -172,7 +172,7 @@ Or on Windows: Elided output from a run of this command on UNIX is shown below: -.. code-block:: text +.. code-block:: bash $ cd MyProject $ $VENV/bin/python setup.py develop @@ -198,7 +198,7 @@ directory of your virtualenv). On UNIX: -.. code-block:: text +.. code-block:: bash $ $VENV/bin/python setup.py test -q @@ -210,7 +210,7 @@ Or on Windows: Here's sample output from a test run on UNIX: -.. code-block:: text +.. code-block:: bash $ $VENV/bin/python setup.py test -q running test @@ -221,11 +221,23 @@ Here's sample output from a test run on UNIX: writing dependency_links to MyProject.egg-info/dependency_links.txt writing entry points to MyProject.egg-info/entry_points.txt reading manifest file 'MyProject.egg-info/SOURCES.txt' + reading manifest template 'MANIFEST.in' + warning: no files found matching '*.cfg' + warning: no files found matching '*.rst' + warning: no files found matching '*.ico' under directory 'myproject' + warning: no files found matching '*.gif' under directory 'myproject' + warning: no files found matching '*.jpg' under directory 'myproject' + warning: no files found matching '*.txt' under directory 'myproject' + warning: no files found matching '*.mak' under directory 'myproject' + warning: no files found matching '*.mako' under directory 'myproject' + warning: no files found matching '*.js' under directory 'myproject' + warning: no files found matching '*.html' under directory 'myproject' + warning: no files found matching '*.xml' under directory 'myproject' writing manifest file 'MyProject.egg-info/SOURCES.txt' running build_ext - .. + . ---------------------------------------------------------------------- - Ran 1 test in 0.108s + Ran 1 test in 0.008s OK @@ -256,7 +268,7 @@ file. In our case, this file is named ``development.ini``. On UNIX: -.. code-block:: text +.. code-block:: bash $ $VENV/bin/pserve development.ini @@ -268,38 +280,38 @@ On Windows: Here's sample output from a run of ``pserve`` on UNIX: -.. code-block:: text +.. code-block:: bash $ $VENV/bin/pserve development.ini - Starting server in PID 16601. - serving on http://0.0.0.0:6543 - -When you use ``pserve`` to start the application implied by the default -rendering of a scaffold, it will respond to requests on *all* IP addresses -possessed by your system, not just requests to ``localhost``. This is what the -``0.0.0.0`` in ``serving on http://0.0.0.0:6543`` means. The server will -respond to requests made to ``127.0.0.1`` and on any external IP address. For -example, your system might be configured to have an external IP address -``192.168.1.50``. If that's the case, if you use a browser running on the same -system as Pyramid, it will be able to access the application via -``http://127.0.0.1:6543/`` as well as via ``http://192.168.1.50:6543/``. -However, *other people* on other computers on the same network will also be -able to visit your Pyramid application in their browser by visiting -``http://192.168.1.50:6543/``. - -If you want to restrict access such that only a browser running on the same -machine as Pyramid will be able to access your Pyramid application, edit the + Starting server in PID 16208. + serving on http://127.0.0.1:6543 + +Access is restricted such that only a browser running on the same machine as +Pyramid will be able to access your Pyramid application. However, if you want +to open access to other machines on the same network, then edit the ``development.ini`` file, and replace the ``host`` value in the -``[server:main]`` section. Change it from ``0.0.0.0`` to ``127.0.0.1``. For +``[server:main]`` section, changing it from ``127.0.0.1`` to ``0.0.0.0``. For example: .. code-block:: ini [server:main] use = egg:waitress#main - host = 127.0.0.1 + host = 0.0.0.0 port = 6543 +Now when you use ``pserve`` to start the application, it will respond to +requests on *all* IP addresses possessed by your system, not just requests to +``localhost``. This is what the ``0.0.0.0`` in +``serving on http://0.0.0.0:6543`` means. The server will respond to requests +made to ``127.0.0.1`` and on any external IP address. For example, your system +might be configured to have an external IP address ``192.168.1.50``. If that's +the case, if you use a browser running on the same system as Pyramid, it will +be able to access the application via ``http://127.0.0.1:6543/`` as well as via +``http://192.168.1.50:6543/``. However, *other people* on other computers on +the same network will also be able to visit your Pyramid application in their +browser by visiting ``http://192.168.1.50:6543/``. + You can change the port on which the server runs on by changing the same portion of the ``development.ini`` file. For example, you can change the ``port = 6543`` line in the ``development.ini`` file's ``[server:main]`` @@ -347,7 +359,7 @@ For example, on UNIX: $ $VENV/bin/pserve development.ini --reload Starting subprocess with file monitor Starting server in PID 16601. - serving on http://0.0.0.0:6543 + serving on http://127.0.0.1:6543 Now if you make a change to any of your project's ``.py`` files or ``.ini`` files, you'll see the server restart automatically: @@ -357,7 +369,7 @@ files, you'll see the server restart automatically: development.ini changed; reloading... -------------------- Restarting -------------------- Starting server in PID 16602. - serving on http://0.0.0.0:6543 + serving on http://127.0.0.1:6543 Changes to template files (such as ``.pt`` or ``.mak`` files) won't cause the server to restart. Changes to template files don't require a server restart as @@ -579,18 +591,16 @@ file. The name ``main`` is a convention used by PasteDeploy signifying that it is the default application. The ``[server:main]`` section of the configuration file configures a WSGI -server which listens on TCP port 6543. It is configured to listen on all -interfaces (``0.0.0.0``). This means that any remote system which has TCP -access to your system can see your Pyramid application. +server which listens on TCP port 6543. It is configured to listen on localhost +only (``127.0.0.1``). .. _MyProject_ini_logging: -The sections that live between the markers ``# Begin logging configuration`` -and ``# End logging configuration`` represent Python's standard library -:mod:`logging` module configuration for your application. The sections between -these two markers are passed to the `logging module's config file configuration -engine `_ when -the ``pserve`` or ``pshell`` commands are executed. The default configuration +The sections after ``# logging configuration`` represent Python's standard +library :mod:`logging` module configuration for your application. These +sections are passed to the `logging module's config file configuration engine +`_ when the +``pserve`` or ``pshell`` commands are executed. The default configuration sends application logging output to the standard error output of your terminal. For more information about logging configuration, see :ref:`logging_chapter`. @@ -912,7 +922,7 @@ The ``tests.py`` module includes unit tests for your application. .. literalinclude:: MyProject/myproject/tests.py :language: python - :lines: 1-18 + :lines: 1-17 :linenos: This sample ``tests.py`` file has a single unit test defined within it. This -- cgit v1.2.3 From bf8014ec3458b46c427706988a8ca26380707cd7 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 8 Dec 2015 02:43:14 -0800 Subject: update narrative docs and literalinclude source files that use the starter scaffold to reflect its current state --- docs/narr/startup.rst | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) (limited to 'docs') diff --git a/docs/narr/startup.rst b/docs/narr/startup.rst index 485f6b181..3e168eaea 100644 --- a/docs/narr/startup.rst +++ b/docs/narr/startup.rst @@ -6,15 +6,15 @@ Startup When you cause a :app:`Pyramid` application to start up in a console window, you'll see something much like this show up on the console: -.. code-block:: text +.. code-block:: bash - $ pserve development.ini - Starting server in PID 16601. - serving on 0.0.0.0:6543 view at http://127.0.0.1:6543 + $ $VENV/bin/pserve development.ini + Starting server in PID 16305. + serving on http://127.0.0.1:6543 This chapter explains what happens between the time you press the "Return" key on your keyboard after typing ``pserve development.ini`` and the time the line -``serving on 0.0.0.0:6543 ...`` is output to your console. +``serving on http://127.0.0.1:6543`` is output to your console. .. index:: single: startup process @@ -92,11 +92,11 @@ Here's a high-level time-ordered overview of what happens when you press In this case, the ``myproject.__init__:main`` function referred to by the entry point URI ``egg:MyProject`` (see :ref:`MyProject_ini` for more information about entry point URIs, and how they relate to callables) will - receive the key/value pairs ``{'pyramid.reload_templates':'true', - 'pyramid.debug_authorization':'false', 'pyramid.debug_notfound':'false', - 'pyramid.debug_routematch':'false', 'pyramid.debug_templates':'true', - 'pyramid.default_locale_name':'en'}``. See :ref:`environment_chapter` for - the meanings of these keys. + receive the key/value pairs ``{pyramid.reload_templates = true, + pyramid.debug_authorization = false, pyramid.debug_notfound = false, + pyramid.debug_routematch = false, pyramid.default_locale_name = en, and + pyramid.includes = pyramid_debugtoolbar}``. See :ref:`environment_chapter` + for the meanings of these keys. #. The ``main`` function first constructs a :class:`~pyramid.config.Configurator` instance, passing the ``settings`` @@ -131,10 +131,9 @@ Here's a high-level time-ordered overview of what happens when you press #. ``pserve`` starts the WSGI *server* defined within the ``[server:main]`` section. In our case, this is the Waitress server (``use = egg:waitress#main``), and it will listen on all interfaces (``host = - 0.0.0.0``), on port number 6543 (``port = 6543``). The server code itself - is what prints ``serving on 0.0.0.0:6543 view at http://127.0.0.1:6543``. - The server serves the application, and the application is running, waiting - to receive requests. + 127.0.0.1``), on port number 6543 (``port = 6543``). The server code itself + is what prints ``serving on http://127.0.0.1:6543``. The server serves the + application, and the application is running, waiting to receive requests. .. seealso:: Logging configuration is described in the :ref:`logging_chapter` chapter. -- cgit v1.2.3 From eedef93f0c4c52ea11320bcd49386262fa7293a1 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Tue, 8 Dec 2015 11:12:38 -0600 Subject: update the cache busting narrative to use add_cache_buster --- docs/narr/assets.rst | 103 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 72 insertions(+), 31 deletions(-) (limited to 'docs') diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 0f819570c..8b41f9b8a 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -366,8 +366,7 @@ resource and requests the asset, regardless of any caching policy set for the resource's old URL. :app:`Pyramid` can be configured to produce cache busting URLs for static -assets by passing the optional argument, ``cachebust`` to -:meth:`~pyramid.config.Configurator.add_static_view`: +assets using :meth:`~pyramid.config.Configurator.add_cache_buster`: .. code-block:: python :linenos: @@ -376,14 +375,18 @@ assets by passing the optional argument, ``cachebust`` to from pyramid.static import QueryStringConstantCacheBuster # config is an instance of pyramid.config.Configurator - config.add_static_view( - name='static', path='mypackage:folder/static', - cachebust=QueryStringConstantCacheBuster(str(int(time.time()))), - ) + config.add_static_view(name='static', path='mypackage:folder/static/') + config.add_cache_buster( + 'mypackage:folder/static/', + QueryStringConstantCacheBuster(str(int(time.time())))) + +.. note:: + The trailing slash on the ``add_cache_buster`` call is important to + indicate that it is overriding every asset in the folder and not just a + file named ``static``. -Setting the ``cachebust`` argument instructs :app:`Pyramid` to use a cache -busting scheme which adds the curent time for a static asset to the query -string in the asset's URL: +Adding the cachebuster instructs :app:`Pyramid` to add the current time for +a static asset to the query string in the asset's URL: .. code-block:: python :linenos: @@ -392,10 +395,7 @@ string in the asset's URL: # Returns: 'http://www.example.com/static/js/myapp.js?x=1445318121' When the web server restarts, the time constant will change and therefore so -will its URL. Supplying the ``cachebust`` argument also causes the static -view to set headers instructing clients to cache the asset for ten years, -unless the ``cache_max_age`` argument is also passed, in which case that -value is used. +will its URL. .. note:: @@ -410,7 +410,7 @@ Disabling the Cache Buster It can be useful in some situations (e.g., development) to globally disable all configured cache busters without changing calls to -:meth:`~pyramid.config.Configurator.add_static_view`. To do this set the +:meth:`~pyramid.config.Configurator.add_cache_buster`. To do this set the ``PYRAMID_PREVENT_CACHEBUST`` environment variable or the ``pyramid.prevent_cachebust`` configuration value to a true value. @@ -419,9 +419,9 @@ configured cache busters without changing calls to Customizing the Cache Buster ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The ``cachebust`` option to -:meth:`~pyramid.config.Configurator.add_static_view` may be set to any object -that implements the interface :class:`~pyramid.interfaces.ICacheBuster`. +Calls to :meth:`~pyramid.config.Configurator.add_cache_buster` may use +any object that implements the interface +:class:`~pyramid.interfaces.ICacheBuster`. :app:`Pyramid` ships with a very simplistic :class:`~pyramid.static.QueryStringConstantCacheBuster`, which adds an @@ -461,8 +461,30 @@ the hash of the current commit: def tokenize(self, pathspec): return self.sha1 -Choosing a Cache Buster -~~~~~~~~~~~~~~~~~~~~~~~ +A simple cache buster that modifies the path segment can be constructed as +well: + +.. code-block:: python + :linenos: + + import posixpath + + def cache_buster(spec, subpath, kw): + base_subpath, ext = posixpath.splitext(subpath) + new_subpath = base_subpath + '-asdf' + ext + return new_subpath, kw + +The caveat with this approach is that modifying the path segment +changes the file name, and thus must match what is actually on the +filesystem in order for :meth:`~pyramid.config.Configurator.add_static_view` +to find the file. It's better to use the +:class:`~pyramid.static.ManifestCacheBuster` for these situations, as +described in the next section. + +.. _path_segment_cache_busters: + +Path Segments and Choosing a Cache Buster +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Many caching HTTP proxies will fail to cache a resource if the URL contains a query string. Therefore, in general, you should prefer a cache busting @@ -504,8 +526,11 @@ The following code would set up a cachebuster: config.add_static_view( name='http://mycdn.example.com/', - path='mypackage:static', - cachebust=ManifestCacheBuster('myapp:static/manifest.json')) + path='mypackage:static') + + config.add_cache_buster( + 'mypackage:static/', + ManifestCacheBuster('myapp:static/manifest.json')) A simpler approach is to use the :class:`~pyramid.static.QueryStringConstantCacheBuster` to generate a global @@ -524,8 +549,11 @@ start up as a cachebust token: config.add_static_view( name='http://mycdn.example.com/', - path='mypackage:static', - cachebust=QueryStringConstantCacheBuster(str(int(time.time())))) + path='mypackage:static') + + config.add_cache_buster( + 'mypackage:static/', + QueryStringConstantCacheBuster(str(int(time.time())))) .. index:: single: static assets view @@ -536,25 +564,38 @@ CSS and JavaScript source and cache busting Often one needs to refer to images and other static assets inside CSS and JavaScript files. If cache busting is active, the final static asset URL is not available until the static assets have been assembled. These URLs cannot be -handwritten. Thus, when having static asset references in CSS and JavaScript, -one needs to perform one of the following tasks: +handwritten. Below is an example of how to integrate the cache buster into +the entire stack. Remember, it is just an example and should be modified to +fit your specific tools. -* Process the files by using a precompiler which rewrites URLs to their final - cache busted form. Then, you can use the +* First, process the files by using a precompiler which rewrites URLs to their + final cache-busted form. Then, you can use the :class:`~pyramid.static.ManifestCacheBuster` to synchronize your asset pipeline with :app:`Pyramid`, allowing the pipeline to have full control over the final URLs of your assets. -* Templatize JS and CSS, and call ``request.static_url()`` inside their - template code. +Now that you are able to generate static URLs within :app:`Pyramid`, +you'll need to handle URLs that are out of our control. To do this you may +use some of the following options to get started: -* Pass static URL references to CSS and JavaScript via other means. +* Configure your asset pipeline to rewrite URL references inline in + CSS and JavaScript. This is the best approach because then the files + may be hosted by :app:`Pyramid` or an external CDN without haven't to + change anything. They really are static. + +* Templatize JS and CSS, and call ``request.static_url()`` inside their + template code. While this approach may work in certain scenarios, it is not + recommended because your static assets will not really be static and are now + dependent on :app:`Pyramid` to be served correctly. See + :ref:`advanced static` for more information on this approach. If your CSS and JavaScript assets use URLs to reference other assets it is recommended that you implement an external asset pipeline that can rewrite the generated static files with new URLs containing cache busting tokens. The machinery inside :app:`Pyramid` will not help with this step as it has very -little knowledge of the asset types your application may use. +little knowledge of the asset types your application may use. The integration +into :app:`Pyramid` is simply for linking those assets into your HTML and +other dynamic content. .. _advanced_static: -- cgit v1.2.3 From 3175c990bc02805b729594996f6360b81f5f0ebc Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Wed, 9 Dec 2015 23:01:35 -0600 Subject: fix broken ref in docs --- docs/narr/assets.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 8b41f9b8a..0e3f6af11 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -587,7 +587,7 @@ use some of the following options to get started: template code. While this approach may work in certain scenarios, it is not recommended because your static assets will not really be static and are now dependent on :app:`Pyramid` to be served correctly. See - :ref:`advanced static` for more information on this approach. + :ref:`advanced_static` for more information on this approach. If your CSS and JavaScript assets use URLs to reference other assets it is recommended that you implement an external asset pipeline that can rewrite the -- cgit v1.2.3 From 312aa1b996f786dc18d8189a7a6d9813ad609645 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 14 Dec 2015 02:26:32 -0800 Subject: - Remove broken integration test example from testing and source file, per #2172 - Update functional test with explicit instructions and to sync with actual starter scaffold --- docs/narr/MyProject/myproject/tests.py | 26 ------------ docs/narr/testing.rst | 73 +++++++++++++++++++--------------- 2 files changed, 42 insertions(+), 57 deletions(-) (limited to 'docs') diff --git a/docs/narr/MyProject/myproject/tests.py b/docs/narr/MyProject/myproject/tests.py index 63d00910c..37df08a2a 100644 --- a/docs/narr/MyProject/myproject/tests.py +++ b/docs/narr/MyProject/myproject/tests.py @@ -17,32 +17,6 @@ class ViewTests(unittest.TestCase): self.assertEqual(info['project'], 'MyProject') -class ViewIntegrationTests(unittest.TestCase): - def setUp(self): - """ This sets up the application registry with the - registrations your application declares in its ``includeme`` - function. - """ - self.config = testing.setUp() - self.config.include('myproject') - - def tearDown(self): - """ Clear out the application registry """ - testing.tearDown() - - def test_my_view(self): - from myproject.views import my_view - request = testing.DummyRequest() - result = my_view(request) - self.assertEqual(result.status, '200 OK') - body = result.app_iter[0] - self.assertTrue('Welcome to' in body) - self.assertEqual(len(result.headerlist), 2) - self.assertEqual(result.headerlist[0], - ('Content-Type', 'text/html; charset=UTF-8')) - self.assertEqual(result.headerlist[1], ('Content-Length', - str(len(body)))) - class FunctionalTests(unittest.TestCase): def setUp(self): from myproject import main diff --git a/docs/narr/testing.rst b/docs/narr/testing.rst index c05ee41ad..a3f62058b 100644 --- a/docs/narr/testing.rst +++ b/docs/narr/testing.rst @@ -348,26 +348,6 @@ code's integration with the rest of :app:`Pyramid`. See also :ref:`including_configuration` -Let's demonstrate this by showing an integration test for a view. - -Given the following view definition, which assumes that your application's -:term:`package` name is ``myproject``, and within that :term:`package` there -exists a module ``views``, which in turn contains a :term:`view` function named -``my_view``: - - .. literalinclude:: MyProject/myproject/views.py - :linenos: - :lines: 1-6 - :language: python - -You'd then create a ``tests`` module within your ``myproject`` package, -containing the following test code: - - .. literalinclude:: MyProject/myproject/tests.py - :linenos: - :pyobject: ViewIntegrationTests - :language: python - Writing unit tests that use the :class:`~pyramid.config.Configurator` API to set up the right "mock" registrations is often preferred to creating integration tests. Unit tests will run faster (because they do less for each @@ -388,22 +368,53 @@ package, which provides APIs for invoking HTTP(S) requests to your application. Regardless of which testing :term:`package` you use, ensure to add a ``tests_require`` dependency on that package to your application's -``setup.py`` file: +``setup.py`` file. Using the project ``MyProject`` generated by the starter +scaffold as described in :doc:`project`, we would insert the following code immediately following the +``requires`` block in the file ``MyProject/setup.py``. - .. literalinclude:: MyProject/setup.py - :linenos: - :emphasize-lines: 26-28,48 - :language: python +.. code-block:: ini + :linenos: + :lineno-start: 11 + :emphasize-lines: 8- + + requires = [ + 'pyramid', + 'pyramid_chameleon', + 'pyramid_debugtoolbar', + 'waitress', + ] + + test_requires = [ + 'webtest', + ] + +Remember to change the dependency. + +.. code-block:: ini + :linenos: + :lineno-start: 39 + :emphasize-lines: 2 + + install_requires=requires, + tests_require=test_requires, + test_suite="myproject", + +As always, whenever you change your dependencies, make sure to run the +following command. + +.. code-block:: bash + + $VENV/bin/python setup.py develop -Let us assume your :term:`package` is named ``myproject`` which contains a -``views`` module, which in turn contains a :term:`view` function ``my_view`` -that returns a HTML body when the root URL is invoked: +In your ``MyPackage`` project, your :term:`package` is named ``myproject`` +which contains a ``views`` module, which in turn contains a :term:`view` +function ``my_view`` that returns an HTML body when the root URL is invoked: .. literalinclude:: MyProject/myproject/views.py :linenos: :language: python -Then the following example functional test demonstrates invoking the above +The following example functional test demonstrates invoking the above :term:`view`: .. literalinclude:: MyProject/myproject/tests.py @@ -414,9 +425,9 @@ Then the following example functional test demonstrates invoking the above When this test is run, each test method creates a "real" :term:`WSGI` application using the ``main`` function in your ``myproject.__init__`` module, using :term:`WebTest` to wrap that WSGI application. It assigns the result to -``self.testapp``. In the test named ``test_root``. The ``TestApp``'s ``GET`` +``self.testapp``. In the test named ``test_root``, the ``TestApp``'s ``GET`` method is used to invoke the root URL. Finally, an assertion is made that the -returned HTML contains the text ``MyProject``. +returned HTML contains the text ``Pyramid``. See the :term:`WebTest` documentation for further information about the methods available to a :class:`webtest.app.TestApp` instance. -- cgit v1.2.3 From 313ff3c28fbd3b784e4c87daf8ae8a4cf713262b Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Wed, 16 Dec 2015 21:30:56 -0600 Subject: update docs to support explicit asset overrides --- docs/narr/assets.rst | 100 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 65 insertions(+), 35 deletions(-) (limited to 'docs') diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 0e3f6af11..b28e6b5b3 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -380,11 +380,6 @@ assets using :meth:`~pyramid.config.Configurator.add_cache_buster`: 'mypackage:folder/static/', QueryStringConstantCacheBuster(str(int(time.time())))) -.. note:: - The trailing slash on the ``add_cache_buster`` call is important to - indicate that it is overriding every asset in the folder and not just a - file named ``static``. - Adding the cachebuster instructs :app:`Pyramid` to add the current time for a static asset to the query string in the asset's URL: @@ -451,12 +446,13 @@ the hash of the current commit: from an egg repository like PYPI, you can use this cachebuster to get the current commit's SHA1 to use as the cache bust token. """ - def __init__(self, param='x'): + def __init__(self, param='x', repo_path=None): super(GitCacheBuster, self).__init__(param=param) - here = os.path.dirname(os.path.abspath(__file__)) + if repo_path is None: + repo_path = os.path.dirname(os.path.abspath(__file__)) self.sha1 = subprocess.check_output( ['git', 'rev-parse', 'HEAD'], - cwd=here).strip() + cwd=repo_path).strip() def tokenize(self, pathspec): return self.sha1 @@ -469,10 +465,14 @@ well: import posixpath - def cache_buster(spec, subpath, kw): - base_subpath, ext = posixpath.splitext(subpath) - new_subpath = base_subpath + '-asdf' + ext - return new_subpath, kw + class PathConstantCacheBuster(object): + def __init__(self, token): + self.token = token + + def __call__(self, request, subpath, kw): + base_subpath, ext = posixpath.splitext(subpath) + new_subpath = base_subpath + self.token + ext + return new_subpath, kw The caveat with this approach is that modifying the path segment changes the file name, and thus must match what is actually on the @@ -532,29 +532,6 @@ The following code would set up a cachebuster: 'mypackage:static/', ManifestCacheBuster('myapp:static/manifest.json')) -A simpler approach is to use the -:class:`~pyramid.static.QueryStringConstantCacheBuster` to generate a global -token that will bust all of the assets at once. The advantage of this strategy -is that it is simple and by using the query string there doesn't need to be -any shared information between your application and the static assets. - -The following code would set up a cachebuster that just uses the time at -start up as a cachebust token: - -.. code-block:: python - :linenos: - - import time - from pyramid.static import QueryStringConstantCacheBuster - - config.add_static_view( - name='http://mycdn.example.com/', - path='mypackage:static') - - config.add_cache_buster( - 'mypackage:static/', - QueryStringConstantCacheBuster(str(int(time.time())))) - .. index:: single: static assets view @@ -834,3 +811,56 @@ when an override is used. As of Pyramid 1.6, it is also possible to override an asset by supplying an absolute path to a file or directory. This may be useful if the assets are not distributed as part of a Python package. + +Cache Busting and Asset Overrides +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Overriding static assets that are being hosted using +:meth:`pyramid.config.Configurator.add_static_view` can affect your cache +busting strategy when using any cache busters that are asset-aware such as +:class:`pyramid.static.ManifestCacheBuster`. What sets asset-aware cache +busters apart is that they have logic tied to specific assets. For example, +a manifest is only generated for a specific set of pre-defined assets. Now, +imagine you have overridden an asset defined in this manifest with a new, +unknown version. By default, the cache buster will be invoked for an asset +it has never seen before and will likely end up returning a cache busting +token for the original asset rather than the asset that will actually end up +being served! In order to get around this issue it's possible to attach a +different :class:`pyramid.interfaces.ICacheBuster` implementation to the +new assets. This would cause the original assets to be served by their +manifest, and the new assets served by their own cache buster. To do this, +:meth:`pyramid.config.Configurator.add_cache_buster` supports an ``explicit`` +option. For example: + +.. code-block:: python + :linenos: + + from pyramid.static import ManifestCacheBuster + + # define a static view for myapp:static assets + config.add_static_view('static', 'myapp:static') + + # setup a cache buster for your app based on the myapp:static assets + my_cb = ManifestCacheBuster('myapp:static/manifest.json') + config.add_cache_buster('myapp:static', my_cb) + + # override an asset + config.override_asset( + to_override='myapp:static/background.png', + override_with='theme:static/background.png') + + # override the cache buster for theme:static assets + theme_cb = ManifestCacheBuster('theme:static/manifest.json') + config.add_cache_buster('theme:static', theme_cb, explicit=True) + +In the above example there is a default cache buster, ``my_cb`` for all assets +served from the ``myapp:static`` folder. This would also affect +``theme:static/background.png`` when generating URLs via +``request.static_url('myapp:static/background.png')``. + +The ``theme_cb`` is defined explicitly for any assets loaded from the +``theme:static`` folder. Explicit cache busters have priority and thus +``theme_cb`` would be invoked for +``request.static_url('myapp:static/background.png')`` but ``my_cb`` would be +used for any other assets like +``request.static_url('myapp:static/favicon.ico')``. -- cgit v1.2.3 From 1dea1477ef7b06fbc1a5de4b434f6b8e6a9d9905 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Thu, 17 Dec 2015 00:11:35 -0800 Subject: progress through "Pyramid Uses a ZCA Registry" - minor grammar, wrap 79 columns --- docs/designdefense.rst | 142 ++++++++++++++++++++++++------------------------- 1 file changed, 69 insertions(+), 73 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index ee6d5a317..478289c2b 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -7,98 +7,94 @@ From time to time, challenges to various aspects of :app:`Pyramid` design are lodged. To give context to discussions that follow, we detail some of the design decisions and trade-offs here. In some cases, we acknowledge that the framework can be made better and we describe future steps which will be taken -to improve it; in some cases we just file the challenge as noted, as -obviously you can't please everyone all of the time. +to improve it. In others we just file the challenge as noted, as obviously you +can't please everyone all of the time. Pyramid Provides More Than One Way to Do It ------------------------------------------- A canon of Python popular culture is "TIOOWTDI" ("there is only one way to do -it", a slighting, tongue-in-cheek reference to Perl's "TIMTOWTDI", which is -an acronym for "there is more than one way to do it"). - -:app:`Pyramid` is, for better or worse, a "TIMTOWTDI" system. For example, -it includes more than one way to resolve a URL to a :term:`view callable`: -via :term:`url dispatch` or :term:`traversal`. Multiple methods of -configuration exist: :term:`imperative configuration`, :term:`configuration -decoration`, and :term:`ZCML` (optionally via :term:`pyramid_zcml`). It works -with multiple different kinds of persistence and templating systems. And so -on. However, the existence of most of these overlapping ways to do things -are not without reason and purpose: we have a number of audiences to serve, -and we believe that TIMTOWTI at the web framework level actually *prevents* a -much more insidious and harmful set of duplication at higher levels in the -Python web community. - -:app:`Pyramid` began its life as :mod:`repoze.bfg`, written by a team of -people with many years of prior :term:`Zope` experience. The idea of +it", a slighting, tongue-in-cheek reference to Perl's "TIMTOWTDI", which is an +acronym for "there is more than one way to do it"). + +:app:`Pyramid` is, for better or worse, a "TIMTOWTDI" system. For example, it +includes more than one way to resolve a URL to a :term:`view callable`: via +:term:`url dispatch` or :term:`traversal`. Multiple methods of configuration +exist: :term:`imperative configuration`, :term:`configuration decoration`, and +:term:`ZCML` (optionally via :term:`pyramid_zcml`). It works with multiple +different kinds of persistence and templating systems. And so on. However, the +existence of most of these overlapping ways to do things are not without reason +and purpose: we have a number of audiences to serve, and we believe that +TIMTOWTDI at the web framework level actually *prevents* a much more insidious +and harmful set of duplication at higher levels in the Python web community. + +:app:`Pyramid` began its life as :mod:`repoze.bfg`, written by a team of people +with many years of prior :term:`Zope` experience. The idea of :term:`traversal` and the way :term:`view lookup` works was stolen entirely from Zope. The authorization subsystem provided by :app:`Pyramid` is a derivative of Zope's. The idea that an application can be *extended* without forking is also a Zope derivative. Implementations of these features were *required* to allow the :app:`Pyramid` -authors to build the bread-and-butter CMS-type systems for customers in the -way in which they were accustomed. No other system, save for Zope itself, -had such features, and Zope itself was beginning to show signs of its age. -We were becoming hampered by consequences of its early design mistakes. -Zope's lack of documentation was also difficult to work around: it was hard -to hire smart people to work on Zope applications, because there was no -comprehensive documentation set to point them at which explained "it all" in -one consumable place, and it was too large and self-inconsistent to document -properly. Before :mod:`repoze.bfg` went under development, its authors -obviously looked around for other frameworks that fit the bill. But no -non-Zope framework did. So we embarked on building :mod:`repoze.bfg`. +authors to build the bread-and-butter CMS-type systems for customers in the way +in which they were accustomed. No other system, save for Zope itself, had such +features, and Zope itself was beginning to show signs of its age. We were +becoming hampered by consequences of its early design mistakes. Zope's lack of +documentation was also difficult to work around. It was hard to hire smart +people to work on Zope applications because there was no comprehensive +documentation set which explained "it all" in one consumable place, and it was +too large and self-inconsistent to document properly. Before :mod:`repoze.bfg` +went under development, its authors obviously looked around for other +frameworks that fit the bill. But no non-Zope framework did. So we embarked on +building :mod:`repoze.bfg`. As the result of our research, however, it became apparent that, despite the -fact that no *one* framework had all the features we required, lots of -existing frameworks had good, and sometimes very compelling ideas. In -particular, :term:`URL dispatch` is a more direct mechanism to map URLs to -code. +fact that no *one* framework had all the features we required, lots of existing +frameworks had good, and sometimes very compelling ideas. In particular, +:term:`URL dispatch` is a more direct mechanism to map URLs to code. So, although we couldn't find a framework, save for Zope, that fit our needs, and while we incorporated a lot of Zope ideas into BFG, we also emulated the features we found compelling in other frameworks (such as :term:`url -dispatch`). After the initial public release of BFG, as time went on, -features were added to support people allergic to various Zope-isms in the -system, such as the ability to configure the application using -:term:`imperative configuration` and :term:`configuration decoration` rather -than solely using :term:`ZCML`, and the elimination of the required use of -:term:`interface` objects. It soon became clear that we had a system that -was very generic, and was beginning to appeal to non-Zope users as well as -ex-Zope users. +dispatch`). After the initial public release of BFG, as time went on, features +were added to support people allergic to various Zope-isms in the system, such +as the ability to configure the application using :term:`imperative +configuration` and :term:`configuration decoration`, rather than solely using +:term:`ZCML`, and the elimination of the required use of :term:`interface` +objects. It soon became clear that we had a system that was very generic, and +was beginning to appeal to non-Zope users as well as ex-Zope users. As the result of this generalization, it became obvious BFG shared 90% of its -featureset with the featureset of Pylons 1, and thus had a very similar -target market. Because they were so similar, choosing between the two -systems was an exercise in frustration for an otherwise non-partisan -developer. It was also strange for the Pylons and BFG development -communities to be in competition for the same set of users, given how similar -the two frameworks were. So the Pylons and BFG teams began to work together -to form a plan to merge. The features missing from BFG (notably :term:`view -handler` classes, flash messaging, and other minor missing bits), were added, -to provide familiarity to ex-Pylons users. The result is :app:`Pyramid`. - -The Python web framework space is currently notoriously balkanized. We're -truly hoping that the amalgamation of components in :app:`Pyramid` will -appeal to at least two currently very distinct sets of users: Pylons and BFG -users. By unifying the best concepts from Pylons and BFG into a single -codebase and leaving the bad concepts from their ancestors behind, we'll be -able to consolidate our efforts better, share more code, and promote our -efforts as a unit rather than competing pointlessly. We hope to be able to -shortcut the pack mentality which results in a *much larger* duplication of -effort, represented by competing but incredibly similar applications and -libraries, each built upon a specific low level stack that is incompatible -with the other. We'll also shrink the choice of credible Python web -frameworks down by at least one. We're also hoping to attract users from -other communities (such as Zope's and TurboGears') by providing the features -they require, while allowing enough flexibility to do things in a familiar -fashion. Some overlap of functionality to achieve these goals is expected -and unavoidable, at least if we aim to prevent pointless duplication at -higher levels. If we've done our job well enough, the various audiences will -be able to coexist and cooperate rather than firing at each other across some -imaginary web framework DMZ. - -Pyramid Uses A Zope Component Architecture ("ZCA") Registry +feature set with the feature set of Pylons 1, and thus had a very similar +target market. Because they were so similar, choosing between the two systems +was an exercise in frustration for an otherwise non-partisan developer. It was +also strange for the Pylons and BFG development communities to be in +competition for the same set of users, given how similar the two frameworks +were. So the Pylons and BFG teams began to work together to form a plan to +merge. The features missing from BFG (notably :term:`view handler` classes, +flash messaging, and other minor missing bits), were added to provide +familiarity to ex-Pylons users. The result is :app:`Pyramid`. + +The Python web framework space is currently notoriously balkanized. We're truly +hoping that the amalgamation of components in :app:`Pyramid` will appeal to at +least two currently very distinct sets of users: Pylons and BFG users. By +unifying the best concepts from Pylons and BFG into a single codebase, and +leaving the bad concepts from their ancestors behind, we'll be able to +consolidate our efforts better, share more code, and promote our efforts as a +unit rather than competing pointlessly. We hope to be able to shortcut the pack +mentality which results in a *much larger* duplication of effort, represented +by competing but incredibly similar applications and libraries, each built upon +a specific low level stack that is incompatible with the other. We'll also +shrink the choice of credible Python web frameworks down by at least one. We're +also hoping to attract users from other communities (such as Zope's and +TurboGears') by providing the features they require, while allowing enough +flexibility to do things in a familiar fashion. Some overlap of functionality +to achieve these goals is expected and unavoidable, at least if we aim to +prevent pointless duplication at higher levels. If we've done our job well +enough, the various audiences will be able to coexist and cooperate rather than +firing at each other across some imaginary web framework DMZ. + +Pyramid Uses a Zope Component Architecture ("ZCA") Registry ----------------------------------------------------------- :app:`Pyramid` uses a :term:`Zope Component Architecture` (ZCA) "component -- cgit v1.2.3 From 897d1deeab710233565f97d216e4d112b2a466e3 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Thu, 17 Dec 2015 20:52:19 -0600 Subject: grammar updates from stevepiercy --- docs/narr/assets.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'docs') diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index b28e6b5b3..054c58247 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -557,7 +557,7 @@ use some of the following options to get started: * Configure your asset pipeline to rewrite URL references inline in CSS and JavaScript. This is the best approach because then the files - may be hosted by :app:`Pyramid` or an external CDN without haven't to + may be hosted by :app:`Pyramid` or an external CDN without having to change anything. They really are static. * Templatize JS and CSS, and call ``request.static_url()`` inside their @@ -825,7 +825,7 @@ imagine you have overridden an asset defined in this manifest with a new, unknown version. By default, the cache buster will be invoked for an asset it has never seen before and will likely end up returning a cache busting token for the original asset rather than the asset that will actually end up -being served! In order to get around this issue it's possible to attach a +being served! In order to get around this issue, it's possible to attach a different :class:`pyramid.interfaces.ICacheBuster` implementation to the new assets. This would cause the original assets to be served by their manifest, and the new assets served by their own cache buster. To do this, @@ -853,14 +853,14 @@ option. For example: theme_cb = ManifestCacheBuster('theme:static/manifest.json') config.add_cache_buster('theme:static', theme_cb, explicit=True) -In the above example there is a default cache buster, ``my_cb`` for all assets -served from the ``myapp:static`` folder. This would also affect +In the above example there is a default cache buster, ``my_cb``, for all +assets served from the ``myapp:static`` folder. This would also affect ``theme:static/background.png`` when generating URLs via ``request.static_url('myapp:static/background.png')``. The ``theme_cb`` is defined explicitly for any assets loaded from the ``theme:static`` folder. Explicit cache busters have priority and thus ``theme_cb`` would be invoked for -``request.static_url('myapp:static/background.png')`` but ``my_cb`` would be -used for any other assets like +``request.static_url('myapp:static/background.png')``, but ``my_cb`` would +be used for any other assets like ``request.static_url('myapp:static/favicon.ico')``. -- cgit v1.2.3 From 50dd2e4c7d8f5ab8de79c490e304b44916183f77 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 20 Dec 2015 14:00:12 -0800 Subject: add sphinxcontrib-programoutput configuration to render command line output --- docs/conf.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/conf.py b/docs/conf.py index 8a9bac6ed..073811eca 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -53,12 +53,13 @@ extensions = [ 'sphinx.ext.doctest', 'repoze.sphinx.autointerface', 'sphinx.ext.viewcode', - 'sphinx.ext.intersphinx' + 'sphinx.ext.intersphinx', + 'sphinxcontrib.programoutput', ] # Looks for objects in external projects intersphinx_mapping = { - 'colander': ( 'http://docs.pylonsproject.org/projects/colander/en/latest', None), + 'colander': ('http://docs.pylonsproject.org/projects/colander/en/latest', None), 'cookbook': ('http://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/', None), 'deform': ('http://docs.pylonsproject.org/projects/deform/en/latest', None), 'jinja2': ('http://docs.pylonsproject.org/projects/pyramid-jinja2/en/latest/', None), @@ -66,8 +67,8 @@ intersphinx_mapping = { 'python': ('http://docs.python.org', None), 'python3': ('http://docs.python.org/3', None), 'sqla': ('http://docs.sqlalchemy.org/en/latest', None), - 'tm': ('http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/', None), - 'toolbar': ('http://docs.pylonsproject.org/projects/pyramid-debugtoolbar/en/latest', None), + 'tm': ('http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/', None), + 'toolbar': ('http://docs.pylonsproject.org/projects/pyramid-debugtoolbar/en/latest', None), 'tstring': ('http://docs.pylonsproject.org/projects/translationstring/en/latest', None), 'tutorials': ('http://docs.pylonsproject.org/projects/pyramid-tutorials/en/latest/', None), 'venusian': ('http://docs.pylonsproject.org/projects/venusian/en/latest', None), -- cgit v1.2.3 From 5ff3d2dfdbf936d115e3486696401ad7dbffedc3 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 21 Dec 2015 01:24:34 -0800 Subject: - add p* scripts - add links to p* scripts - add a blank line to keep indices and labels better visually related to the subsequent heading --- docs/index.rst | 13 +++++++++++++ docs/narr/commandline.rst | 33 +++++++++++++++++++++++++++++++++ docs/narr/project.rst | 6 ++++++ docs/pscripts/index.rst | 12 ++++++++++++ docs/pscripts/pcreate.rst | 14 ++++++++++++++ docs/pscripts/pdistreport.rst | 14 ++++++++++++++ docs/pscripts/prequest.rst | 14 ++++++++++++++ docs/pscripts/proutes.rst | 14 ++++++++++++++ docs/pscripts/pserve.rst | 14 ++++++++++++++ docs/pscripts/pshell.rst | 14 ++++++++++++++ docs/pscripts/ptweens.rst | 14 ++++++++++++++ docs/pscripts/pviews.rst | 14 ++++++++++++++ 12 files changed, 176 insertions(+) create mode 100644 docs/pscripts/index.rst create mode 100644 docs/pscripts/pcreate.rst create mode 100644 docs/pscripts/pdistreport.rst create mode 100644 docs/pscripts/prequest.rst create mode 100644 docs/pscripts/proutes.rst create mode 100644 docs/pscripts/pserve.rst create mode 100644 docs/pscripts/pshell.rst create mode 100644 docs/pscripts/ptweens.rst create mode 100644 docs/pscripts/pviews.rst (limited to 'docs') diff --git a/docs/index.rst b/docs/index.rst index e792b9905..8c8a0a18d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -162,6 +162,19 @@ Comprehensive reference material for every public API exposed by api/* +``p*`` Scripts Documentation +============================ + +``p*`` scripts included with :app:`Pyramid`:. + +.. toctree:: + :maxdepth: 1 + :glob: + + pscripts/index + pscripts/* + + Change History ============== diff --git a/docs/narr/commandline.rst b/docs/narr/commandline.rst index eb79dffb6..34b12e1e9 100644 --- a/docs/narr/commandline.rst +++ b/docs/narr/commandline.rst @@ -6,6 +6,7 @@ Command-Line Pyramid Your :app:`Pyramid` application can be controlled and inspected using a variety of command-line utilities. These utilities are documented in this chapter. + .. index:: pair: matching views; printing single: pviews @@ -15,6 +16,8 @@ of command-line utilities. These utilities are documented in this chapter. Displaying Matching Views for a Given URL ----------------------------------------- +.. seealso:: See also the output of :ref:`pviews --help `. + For a big application with several views, it can be hard to keep the view configuration details in your head, even if you defined all the views yourself. You can use the ``pviews`` command in a terminal window to print a summary of @@ -114,6 +117,8 @@ found* message. The Interactive Shell --------------------- +.. seealso:: See also the output of :ref:`pshell --help `. + Once you've installed your program for development using ``setup.py develop``, you can use an interactive Python shell to execute expressions in a Python environment exactly like the one that will be used when your application runs @@ -179,6 +184,7 @@ hash after the filename: Press ``Ctrl-D`` to exit the interactive shell (or ``Ctrl-Z`` on Windows). + .. index:: pair: pshell; extending @@ -261,6 +267,7 @@ request is configured to generate urls from the host >>> request.route_url('home') 'https://www.example.com/' + .. _ipython_or_bpython: Alternative Shells @@ -317,6 +324,7 @@ arguments, ``env`` and ``help``, which would look like this: ``ipython`` and ``bpython`` have been moved into their respective packages ``pyramid_ipython`` and ``pyramid_bpython``. + Setting a Default Shell ~~~~~~~~~~~~~~~~~~~~~~~ @@ -331,6 +339,7 @@ specify a list of preferred shells. .. versionadded:: 1.6 + .. index:: pair: routes; printing single: proutes @@ -340,6 +349,8 @@ specify a list of preferred shells. Displaying All Application Routes --------------------------------- +.. seealso:: See also the output of :ref:`proutes --help `. + You can use the ``proutes`` command in a terminal window to print a summary of routes related to your application. Much like the ``pshell`` command (see :ref:`interactive_shell`), the ``proutes`` command accepts one argument with @@ -421,6 +432,8 @@ include. The current available formats are ``name``, ``pattern``, ``view``, and Displaying "Tweens" ------------------- +.. seealso:: See also the output of :ref:`ptweens --help `. + A :term:`tween` is a bit of code that sits between the main Pyramid application request handler and the WSGI application which calls it. A user can get a representation of both the implicit tween ordering (the ordering specified by @@ -497,6 +510,7 @@ used: See :ref:`registering_tweens` for more information about tweens. + .. index:: single: invoking a request single: prequest @@ -506,6 +520,8 @@ See :ref:`registering_tweens` for more information about tweens. Invoking a Request ------------------ +.. seealso:: See also the output of :ref:`prequest --help `. + You can use the ``prequest`` command-line utility to send a request to your application and see the response body without starting a server. @@ -555,6 +571,7 @@ of the ``prequest`` process is used as the ``POST`` body:: $ $VENV/bin/prequest -mPOST development.ini / < somefile + Using Custom Arguments to Python when Running ``p*`` Scripts ------------------------------------------------------------ @@ -566,11 +583,22 @@ Python interpreter at runtime. For example:: python -3 -m pyramid.scripts.pserve development.ini + +.. index:: + single: pdistreport + single: distributions, showing installed + single: showing installed distributions + +.. _showing_distributions: + Showing All Installed Distributions and Their Versions ------------------------------------------------------ .. versionadded:: 1.5 +.. seealso:: See also the output of :ref:`pdistreport --help + `. + You can use the ``pdistreport`` command to show the :app:`Pyramid` version in use, the Python version in use, and all installed versions of Python distributions in your Python environment:: @@ -590,6 +618,7 @@ pastebin when you are having problems and need someone with more familiarity with Python packaging and distribution than you have to look at your environment. + .. _writing_a_script: Writing a Script @@ -702,6 +731,7 @@ The above example specifies the ``another`` ``app``, ``pipeline``, or object present in the ``env`` dictionary returned by :func:`pyramid.paster.bootstrap` will be a :app:`Pyramid` :term:`router`. + Changing the Request ~~~~~~~~~~~~~~~~~~~~ @@ -742,6 +772,7 @@ Now you can readily use Pyramid's APIs for generating URLs: env['request'].route_url('verify', code='1337') # will return 'https://example.com/prefix/verify/1337' + Cleanup ~~~~~~~ @@ -757,6 +788,7 @@ callback: env['closer']() + Setting Up Logging ~~~~~~~~~~~~~~~~~~ @@ -773,6 +805,7 @@ use the following command: See :ref:`logging_chapter` for more information on logging within :app:`Pyramid`. + .. index:: single: console script diff --git a/docs/narr/project.rst b/docs/narr/project.rst index 4785b60c4..5103bb6b8 100644 --- a/docs/narr/project.rst +++ b/docs/narr/project.rst @@ -53,15 +53,19 @@ The included scaffolds are these: ``alchemy`` URL mapping via :term:`URL dispatch` and persistence via :term:`SQLAlchemy` + .. index:: single: creating a project single: project + single: pcreate .. _creating_a_project: Creating the Project -------------------- +.. seealso:: See also the output of :ref:`pcreate --help `. + In :ref:`installing_chapter`, you created a virtual Python environment via the ``virtualenv`` command. To start a :app:`Pyramid` :term:`project`, use the ``pcreate`` command installed within the virtualenv. We'll choose the @@ -262,6 +266,8 @@ single sample test exists. Running the Project Application ------------------------------- +.. seealso:: See also the output of :ref:`pserve --help `. + Once a project is installed for development, you can run the application it represents using the ``pserve`` command against the generated configuration file. In our case, this file is named ``development.ini``. diff --git a/docs/pscripts/index.rst b/docs/pscripts/index.rst new file mode 100644 index 000000000..1f54546d7 --- /dev/null +++ b/docs/pscripts/index.rst @@ -0,0 +1,12 @@ +.. _pscripts_documentation: + +``p*`` Scripts Documentation +============================ + +``p*`` scripts included with :app:`Pyramid`:. + +.. toctree:: + :maxdepth: 1 + :glob: + + * diff --git a/docs/pscripts/pcreate.rst b/docs/pscripts/pcreate.rst new file mode 100644 index 000000000..4e7f89572 --- /dev/null +++ b/docs/pscripts/pcreate.rst @@ -0,0 +1,14 @@ +.. index:: + single: pcreate; --help + +.. _pcreate_script: + +``pcreate`` +----------- + +.. program-output:: pcreate --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`creating_a_project` diff --git a/docs/pscripts/pdistreport.rst b/docs/pscripts/pdistreport.rst new file mode 100644 index 000000000..37d12d848 --- /dev/null +++ b/docs/pscripts/pdistreport.rst @@ -0,0 +1,14 @@ +.. index:: + single: pdistreport; --help + +.. _pdistreport_script: + +``pdistreport`` +--------------- + +.. program-output:: pdistreport --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`showing_distributions` diff --git a/docs/pscripts/prequest.rst b/docs/pscripts/prequest.rst new file mode 100644 index 000000000..a03d5b0e0 --- /dev/null +++ b/docs/pscripts/prequest.rst @@ -0,0 +1,14 @@ +.. index:: + single: prequest; --help + +.. _prequest_script: + +``prequest`` +------------ + +.. program-output:: prequest --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`invoking_a_request` diff --git a/docs/pscripts/proutes.rst b/docs/pscripts/proutes.rst new file mode 100644 index 000000000..8f3f34e16 --- /dev/null +++ b/docs/pscripts/proutes.rst @@ -0,0 +1,14 @@ +.. index:: + single: proutes; --help + +.. _proutes_script: + +``proutes`` +----------- + +.. program-output:: proutes --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`displaying_application_routes` diff --git a/docs/pscripts/pserve.rst b/docs/pscripts/pserve.rst new file mode 100644 index 000000000..4e41d6e2b --- /dev/null +++ b/docs/pscripts/pserve.rst @@ -0,0 +1,14 @@ +.. index:: + single: pserve; --help + +.. _pserve_script: + +``pserve`` +---------- + +.. program-output:: pserve --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`running_the_project_application` diff --git a/docs/pscripts/pshell.rst b/docs/pscripts/pshell.rst new file mode 100644 index 000000000..fd85a11a9 --- /dev/null +++ b/docs/pscripts/pshell.rst @@ -0,0 +1,14 @@ +.. index:: + single: pshell; --help + +.. _pshell_script: + +``pshell`` +---------- + +.. program-output:: pshell --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`interactive_shell` diff --git a/docs/pscripts/ptweens.rst b/docs/pscripts/ptweens.rst new file mode 100644 index 000000000..e8c0d1ad0 --- /dev/null +++ b/docs/pscripts/ptweens.rst @@ -0,0 +1,14 @@ +.. index:: + single: ptweens; --help + +.. _ptweens_script: + +``ptweens`` +----------- + +.. program-output:: ptweens --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`displaying_tweens` diff --git a/docs/pscripts/pviews.rst b/docs/pscripts/pviews.rst new file mode 100644 index 000000000..a1c2f5c2b --- /dev/null +++ b/docs/pscripts/pviews.rst @@ -0,0 +1,14 @@ +.. index:: + single: pviews; --help + +.. _pviews_script: + +``pviews`` +---------- + +.. program-output:: pviews --help + :cwd: ../../env/bin + :prompt: + :shell: + +.. seealso:: :ref:`displaying_matching_views` -- cgit v1.2.3 From d8101d6e99012bd3a7fcf1806e7d922c8d1371d9 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 21 Dec 2015 21:37:52 -0800 Subject: attempt to get travis to pass on programoutput rst directive --- docs/pscripts/pcreate.rst | 1 - 1 file changed, 1 deletion(-) (limited to 'docs') diff --git a/docs/pscripts/pcreate.rst b/docs/pscripts/pcreate.rst index 4e7f89572..b5ec3f4e2 100644 --- a/docs/pscripts/pcreate.rst +++ b/docs/pscripts/pcreate.rst @@ -7,7 +7,6 @@ ----------- .. program-output:: pcreate --help - :cwd: ../../env/bin :prompt: :shell: -- cgit v1.2.3 From cdb9f7a18725a992f8ad0bfc920c028082222b47 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 21 Dec 2015 21:42:32 -0800 Subject: remove :cwd: argument from programoutput rst directive so that travis will pass --- docs/pscripts/pdistreport.rst | 1 - docs/pscripts/prequest.rst | 1 - docs/pscripts/proutes.rst | 1 - docs/pscripts/pserve.rst | 1 - docs/pscripts/pshell.rst | 1 - docs/pscripts/ptweens.rst | 1 - docs/pscripts/pviews.rst | 1 - 7 files changed, 7 deletions(-) (limited to 'docs') diff --git a/docs/pscripts/pdistreport.rst b/docs/pscripts/pdistreport.rst index 37d12d848..1c53fb6e9 100644 --- a/docs/pscripts/pdistreport.rst +++ b/docs/pscripts/pdistreport.rst @@ -7,7 +7,6 @@ --------------- .. program-output:: pdistreport --help - :cwd: ../../env/bin :prompt: :shell: diff --git a/docs/pscripts/prequest.rst b/docs/pscripts/prequest.rst index a03d5b0e0..a15827767 100644 --- a/docs/pscripts/prequest.rst +++ b/docs/pscripts/prequest.rst @@ -7,7 +7,6 @@ ------------ .. program-output:: prequest --help - :cwd: ../../env/bin :prompt: :shell: diff --git a/docs/pscripts/proutes.rst b/docs/pscripts/proutes.rst index 8f3f34e16..09ed013e1 100644 --- a/docs/pscripts/proutes.rst +++ b/docs/pscripts/proutes.rst @@ -7,7 +7,6 @@ ----------- .. program-output:: proutes --help - :cwd: ../../env/bin :prompt: :shell: diff --git a/docs/pscripts/pserve.rst b/docs/pscripts/pserve.rst index 4e41d6e2b..d33d4a484 100644 --- a/docs/pscripts/pserve.rst +++ b/docs/pscripts/pserve.rst @@ -7,7 +7,6 @@ ---------- .. program-output:: pserve --help - :cwd: ../../env/bin :prompt: :shell: diff --git a/docs/pscripts/pshell.rst b/docs/pscripts/pshell.rst index fd85a11a9..cfd84d4f8 100644 --- a/docs/pscripts/pshell.rst +++ b/docs/pscripts/pshell.rst @@ -7,7 +7,6 @@ ---------- .. program-output:: pshell --help - :cwd: ../../env/bin :prompt: :shell: diff --git a/docs/pscripts/ptweens.rst b/docs/pscripts/ptweens.rst index e8c0d1ad0..02e23e49a 100644 --- a/docs/pscripts/ptweens.rst +++ b/docs/pscripts/ptweens.rst @@ -7,7 +7,6 @@ ----------- .. program-output:: ptweens --help - :cwd: ../../env/bin :prompt: :shell: diff --git a/docs/pscripts/pviews.rst b/docs/pscripts/pviews.rst index a1c2f5c2b..b4de5c054 100644 --- a/docs/pscripts/pviews.rst +++ b/docs/pscripts/pviews.rst @@ -7,7 +7,6 @@ ---------- .. program-output:: pviews --help - :cwd: ../../env/bin :prompt: :shell: -- cgit v1.2.3 From f829b1c82595849e0f7f685f8c559d021748a0d2 Mon Sep 17 00:00:00 2001 From: kpinc Date: Tue, 22 Dec 2015 09:47:12 -0600 Subject: Expound. Punctuation. --- docs/pscripts/index.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/pscripts/index.rst b/docs/pscripts/index.rst index 1f54546d7..857e0564f 100644 --- a/docs/pscripts/index.rst +++ b/docs/pscripts/index.rst @@ -3,7 +3,7 @@ ``p*`` Scripts Documentation ============================ -``p*`` scripts included with :app:`Pyramid`:. +Command line programs (``p*`` scripts) included with :app:`Pyramid`. .. toctree:: :maxdepth: 1 -- cgit v1.2.3 From b7057f3dcac875d71916d6807d157ff6f3ede662 Mon Sep 17 00:00:00 2001 From: Bastien Date: Sat, 26 Dec 2015 14:33:23 -0800 Subject: Update glossary.rst fixed typo (cherry picked from commit 0a5c9a2) --- docs/glossary.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/glossary.rst b/docs/glossary.rst index b4bb36421..60e861597 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -273,7 +273,7 @@ Glossary (Allow, 'bob', 'read'), (Deny, 'fred', 'write')]``. If an ACL is attached to a resource instance, and that resource is findable via the context resource, it will be consulted any active security policy to - determine wither a particular request can be fulfilled given the + determine whether a particular request can be fulfilled given the :term:`authentication` information in the request. authentication -- cgit v1.2.3 From e8609bb3437a4642ce33aa13ca65e84003b397ca Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 30 Dec 2015 02:08:11 -0800 Subject: - minor grammar in "problems", rewrap to 79 columns --- docs/designdefense.rst | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 478289c2b..bfde25246 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -142,7 +142,7 @@ dictionary API, but that's not very important in this context. That's problem number two. Third of all, what does the ``getUtility`` function do? It's performing a -lookup for the ``ISettings`` "utility" that should return.. well, a utility. +lookup for the ``ISettings`` "utility" that should return... well, a utility. Note how we've already built up a dependency on the understanding of an :term:`interface` and the concept of "utility" to answer this question: a bad sign so far. Note also that the answer is circular, a *really* bad sign. @@ -152,12 +152,12 @@ registry" of course. What's a component registry? Problem number four. Fifth, assuming you buy that there's some magical registry hanging around, where *is* this registry? *Homina homina*... "around"? That's sort of the -best answer in this context (a more specific answer would require knowledge -of internals). Can there be more than one registry? Yes. So *which* -registry does it find the registration in? Well, the "current" registry of -course. In terms of :app:`Pyramid`, the current registry is a thread local -variable. Using an API that consults a thread local makes understanding how -it works non-local. +best answer in this context (a more specific answer would require knowledge of +internals). Can there be more than one registry? Yes. So in *which* registry +does it find the registration? Well, the "current" registry of course. In +terms of :app:`Pyramid`, the current registry is a thread local variable. +Using an API that consults a thread local makes understanding how it works +non-local. You've now bought in to the fact that there's a registry that is just hanging around. But how does the registry get populated? Why, via code that calls @@ -166,10 +166,10 @@ registration of ``ISettings`` is made by the framework itself under the hood: it's not present in any user configuration. This is extremely hard to comprehend. Problem number six. -Clearly there's some amount of cognitive load here that needs to be borne by -a reader of code that extends the :app:`Pyramid` framework due to its use of -the ZCA, even if he or she is already an expert Python programmer and whom is -an expert in the domain of web applications. This is suboptimal. +Clearly there's some amount of cognitive load here that needs to be borne by a +reader of code that extends the :app:`Pyramid` framework due to its use of the +ZCA, even if they are already an expert Python programmer and an expert in the +domain of web applications. This is suboptimal. Ameliorations +++++++++++++ -- cgit v1.2.3 From 752d6575d7b86eeb1a7b16eac9476a7620897438 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 2 Jan 2016 22:10:01 -0800 Subject: - minor grammar in "problems", rewrap to 79 columns --- docs/whatsnew-1.5.rst | 2 ++ 1 file changed, 2 insertions(+) (limited to 'docs') diff --git a/docs/whatsnew-1.5.rst b/docs/whatsnew-1.5.rst index 1d863c937..8a769e88e 100644 --- a/docs/whatsnew-1.5.rst +++ b/docs/whatsnew-1.5.rst @@ -136,6 +136,8 @@ Feature Additions The feature additions in Pyramid 1.5 follow. +- Python 3.4 compatibility. + - Add ``pdistreport`` script, which prints the Python version in use, the Pyramid version in use, and the version number and location of all Python distributions currently installed. -- cgit v1.2.3 From 2901e968390f70b4bfa777dd4348dc9d3eb6210c Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sun, 3 Jan 2016 00:22:44 -0600 Subject: add a note about serving cache busted assets --- docs/narr/assets.rst | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'docs') diff --git a/docs/narr/assets.rst b/docs/narr/assets.rst index 054c58247..58f547fc9 100644 --- a/docs/narr/assets.rst +++ b/docs/narr/assets.rst @@ -532,6 +532,14 @@ The following code would set up a cachebuster: 'mypackage:static/', ManifestCacheBuster('myapp:static/manifest.json')) +It's important to note that the cache buster only handles generating +cache-busted URLs for static assets. It does **NOT** provide any solutions for +serving those assets. For example, if you generated a URL for +``css/main-678b7c80.css`` then that URL needs to be valid either by +configuring ``add_static_view`` properly to point to the location of the files +or some other mechanism such as the files existing on your CDN or rewriting +the incoming URL to remove the cache bust tokens. + .. index:: single: static assets view -- cgit v1.2.3 From 41aeac4b9442a03c961b85b896ae84a8da3dbc9c Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sun, 3 Jan 2016 01:06:35 -0600 Subject: fix grammar on whatsnew document titles --- docs/whatsnew-1.0.rst | 2 +- docs/whatsnew-1.1.rst | 2 +- docs/whatsnew-1.2.rst | 2 +- docs/whatsnew-1.3.rst | 2 +- docs/whatsnew-1.4.rst | 2 +- docs/whatsnew-1.5.rst | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) (limited to 'docs') diff --git a/docs/whatsnew-1.0.rst b/docs/whatsnew-1.0.rst index 9541f0a28..0ed6e21fc 100644 --- a/docs/whatsnew-1.0.rst +++ b/docs/whatsnew-1.0.rst @@ -1,4 +1,4 @@ -What's New In Pyramid 1.0 +What's New in Pyramid 1.0 ========================= This article explains the new features in Pyramid version 1.0 as compared to diff --git a/docs/whatsnew-1.1.rst b/docs/whatsnew-1.1.rst index 99737b6d8..a5c7f3393 100644 --- a/docs/whatsnew-1.1.rst +++ b/docs/whatsnew-1.1.rst @@ -1,4 +1,4 @@ -What's New In Pyramid 1.1 +What's New in Pyramid 1.1 ========================= This article explains the new features in Pyramid version 1.1 as compared to diff --git a/docs/whatsnew-1.2.rst b/docs/whatsnew-1.2.rst index a9fc38908..9ff933ace 100644 --- a/docs/whatsnew-1.2.rst +++ b/docs/whatsnew-1.2.rst @@ -1,4 +1,4 @@ -What's New In Pyramid 1.2 +What's New in Pyramid 1.2 ========================= This article explains the new features in :app:`Pyramid` version 1.2 as diff --git a/docs/whatsnew-1.3.rst b/docs/whatsnew-1.3.rst index 2606c3df3..1a299e126 100644 --- a/docs/whatsnew-1.3.rst +++ b/docs/whatsnew-1.3.rst @@ -1,4 +1,4 @@ -What's New In Pyramid 1.3 +What's New in Pyramid 1.3 ========================= This article explains the new features in :app:`Pyramid` version 1.3 as diff --git a/docs/whatsnew-1.4.rst b/docs/whatsnew-1.4.rst index 505b9d798..fce889854 100644 --- a/docs/whatsnew-1.4.rst +++ b/docs/whatsnew-1.4.rst @@ -1,4 +1,4 @@ -What's New In Pyramid 1.4 +What's New in Pyramid 1.4 ========================= This article explains the new features in :app:`Pyramid` version 1.4 as diff --git a/docs/whatsnew-1.5.rst b/docs/whatsnew-1.5.rst index 8a769e88e..a477ce5ec 100644 --- a/docs/whatsnew-1.5.rst +++ b/docs/whatsnew-1.5.rst @@ -1,4 +1,4 @@ -What's New In Pyramid 1.5 +What's New in Pyramid 1.5 ========================= This article explains the new features in :app:`Pyramid` version 1.5 as -- cgit v1.2.3 From 5558386fd1a6181b2e8ad06659049c055a7ed023 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sun, 3 Jan 2016 01:09:52 -0600 Subject: copy whatsnew-1.6 from 1.6-branch --- docs/whatsnew-1.6.rst | 204 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 135 insertions(+), 69 deletions(-) (limited to 'docs') diff --git a/docs/whatsnew-1.6.rst b/docs/whatsnew-1.6.rst index b99ebeec4..bdfcf34ab 100644 --- a/docs/whatsnew-1.6.rst +++ b/docs/whatsnew-1.6.rst @@ -1,40 +1,62 @@ -What's New In Pyramid 1.6 +What's New in Pyramid 1.6 ========================= This article explains the new features in :app:`Pyramid` version 1.6 as -compared to its predecessor, :app:`Pyramid` 1.5. It also documents backwards +compared to its predecessor, :app:`Pyramid` 1.5. It also documents backwards incompatibilities between the two versions and deprecations added to :app:`Pyramid` 1.6, as well as software dependency changes and notable documentation additions. + Backwards Incompatibilities --------------------------- +- IPython and BPython support have been removed from pshell in the core. To + continue using them on Pyramid 1.6+, you must install the binding packages + explicitly. One way to do this is by adding ``pyramid_ipython`` (or + ``pyramid_bpython``) to the ``install_requires`` section of your package's + ``setup.py`` file, then re-running ``setup.py develop``:: + + setup( + #... + install_requires=[ + 'pyramid_ipython', # new dependency + 'pyramid', + #... + ], + ) + - ``request.response`` will no longer be mutated when using the - :func:`~pyramid.renderers.render_to_response` API. It is now necessary - to pass in - a ``response=`` argument to :func:`~pyramid.renderers.render_to_response` if - you wish to supply the renderer with a custom response object for it to - use. If you do not pass one then a response object will be created using the - current response factory. Almost all renderers mutate the - ``request.response`` response object (for example, the JSON renderer sets - ``request.response.content_type`` to ``application/json``). However, when - invoking ``render_to_response`` it is not expected that the response object - being returned would be the same one used later in the request. The response - object returned from ``render_to_response`` is now explicitly different from - ``request.response``. This does not change the API of a renderer. See + :func:`~pyramid.renderers.render_to_response` API. It is now necessary to + pass in a ``response=`` argument to + :func:`~pyramid.renderers.render_to_response` if you wish to supply the + renderer with a custom response object. If you do not pass one, then a + response object will be created using the current response factory. Almost + all renderers mutate the ``request.response`` response object (for example, + the JSON renderer sets ``request.response.content_type`` to + ``application/json``). However, when invoking ``render_to_response``, it is + not expected that the response object being returned would be the same one + used later in the request. The response object returned from + ``render_to_response`` is now explicitly different from ``request.response``. + This does not change the API of a renderer. See https://github.com/Pylons/pyramid/pull/1563 Feature Additions ----------------- -- Cache busting for static assets has been added and is available via a new - argument to :meth:`pyramid.config.Configurator.add_static_view`: - ``cachebust``. Core APIs are shipped for both cache busting via query - strings and path segments and may be extended to fit into custom asset - pipelines. See https://github.com/Pylons/pyramid/pull/1380 and - https://github.com/Pylons/pyramid/pull/1583 +- Python 3.5 and pypy3 compatibility. + +- ``pserve --reload`` will no longer crash on syntax errors. See + https://github.com/Pylons/pyramid/pull/2044 + +- Cache busting for static resources has been added and is available via a new + :meth:`pyramid.config.Configurator.add_cache_buster` API. Core APIs are + shipped for both cache busting via query strings and via asset manifests for + integrating into custom asset pipelines. See + https://github.com/Pylons/pyramid/pull/1380 and + https://github.com/Pylons/pyramid/pull/1583 and + https://github.com/Pylons/pyramid/pull/2171 - Assets can now be overidden by an absolute path on the filesystem when using the :meth:`~pyramid.config.Configurator.override_asset` API. This makes it @@ -47,99 +69,129 @@ Feature Additions ``config.add_static_view('myapp:static', 'static')`` and ``config.override_asset(to_override='myapp:static/', override_with='/abs/path/')``. The ``myapp:static`` asset spec is completely - made up and does not need to exist - it is used for generating urls via - ``request.static_url('myapp:static/foo.png')``. See + made up and does not need to exist—it is used for generating URLs via + ``request.static_url('myapp:static/foo.png')``. See https://github.com/Pylons/pyramid/issues/1252 - Added :meth:`~pyramid.config.Configurator.set_response_factory` and the ``response_factory`` keyword argument to the constructor of :class:`~pyramid.config.Configurator` for defining a factory that will return - a custom ``Response`` class. See https://github.com/Pylons/pyramid/pull/1499 + a custom ``Response`` class. See https://github.com/Pylons/pyramid/pull/1499 -- Add :attr:`pyramid.config.Configurator.root_package` attribute and init - parameter to assist with includeable packages that wish to resolve - resources relative to the package in which the configurator was created. - This is especially useful for addons that need to load asset specs from - settings, in which case it is may be natural for a developer to define - imports or assets relative to the top-level package. - See https://github.com/Pylons/pyramid/pull/1337 +- Added :attr:`pyramid.config.Configurator.root_package` attribute and init + parameter to assist with includible packages that wish to resolve resources + relative to the package in which the configurator was created. This is + especially useful for add-ons that need to load asset specs from settings, in + which case it may be natural for a developer to define imports or assets + relative to the top-level package. See + https://github.com/Pylons/pyramid/pull/1337 - Overall improvments for the ``proutes`` command. Added ``--format`` and ``--glob`` arguments to the command, introduced the ``method`` column for displaying available request methods, and improved the ``view`` - output by showing the module instead of just ``__repr__``. - See https://github.com/Pylons/pyramid/pull/1488 + output by showing the module instead of just ``__repr__``. See + https://github.com/Pylons/pyramid/pull/1488 - ``pserve`` can now take a ``-b`` or ``--browser`` option to open the server URL in a web browser. See https://github.com/Pylons/pyramid/pull/1533 -- Support keyword-only arguments and function annotations in views in - Python 3. See https://github.com/Pylons/pyramid/pull/1556 +- Support keyword-only arguments and function annotations in views in Python 3. + See https://github.com/Pylons/pyramid/pull/1556 - The ``append_slash`` argument of :meth:`~pyramid.config.Configurator.add_notfound_view()` will now accept anything that implements the :class:`~pyramid.interfaces.IResponse` interface and will use that as the response class instead of the default - :class:`~pyramid.httpexceptions.HTTPFound`. See + :class:`~pyramid.httpexceptions.HTTPFound`. See https://github.com/Pylons/pyramid/pull/1610 - The :class:`~pyramid.config.Configurator` has grown the ability to allow - actions to call other actions during a commit-cycle. This enables much more + actions to call other actions during a commit cycle. This enables much more logic to be placed into actions, such as the ability to invoke other actions or group them for improved conflict detection. We have also exposed and - documented the config phases that Pyramid uses in order to further assist in - building conforming addons. See https://github.com/Pylons/pyramid/pull/1513 + documented the configuration phases that Pyramid uses in order to further + assist in building conforming add-ons. See + https://github.com/Pylons/pyramid/pull/1513 - Allow an iterator to be returned from a renderer. Previously it was only - possible to return bytes or unicode. - See https://github.com/Pylons/pyramid/pull/1417 + possible to return bytes or unicode. See + https://github.com/Pylons/pyramid/pull/1417 - Improve robustness to timing attacks in the :class:`~pyramid.authentication.AuthTktCookieHelper` and the :class:`~pyramid.session.SignedCookieSessionFactory` classes by using the - stdlib's ``hmac.compare_digest`` if it is available (such as Python 2.7.7+ and - 3.3+). See https://github.com/Pylons/pyramid/pull/1457 + stdlib's ``hmac.compare_digest`` if it is available (such as Python 2.7.7+ + and 3.3+). See https://github.com/Pylons/pyramid/pull/1457 -- Improve the readability of the ``pcreate`` shell script output. - See https://github.com/Pylons/pyramid/pull/1453 +- Improve the readability of the ``pcreate`` shell script output. See + https://github.com/Pylons/pyramid/pull/1453 -- Make it simple to define notfound and forbidden views that wish to use the - default exception-response view but with altered predicates and other - configuration options. The ``view`` argument is now optional in +- Make it simple to define ``notfound`` and ``forbidden`` views that wish to + use the default exception-response view, but with altered predicates and + other configuration options. The ``view`` argument is now optional in :meth:`~pyramid.config.Configurator.add_notfound_view` and :meth:`~pyramid.config.Configurator.add_forbidden_view` See https://github.com/Pylons/pyramid/issues/494 - The ``pshell`` script will now load a ``PYTHONSTARTUP`` file if one is - defined in the environment prior to launching the interpreter. - See https://github.com/Pylons/pyramid/pull/1448 + defined in the environment prior to launching the interpreter. See + https://github.com/Pylons/pyramid/pull/1448 -- Add new HTTP exception objects for status codes - ``428 Precondition Required``, ``429 Too Many Requests`` and - ``431 Request Header Fields Too Large`` in ``pyramid.httpexceptions``. - See https://github.com/Pylons/pyramid/pull/1372/files +- Add new HTTP exception objects for status codes ``428 Precondition + Required``, ``429 Too Many Requests`` and ``431 Request Header Fields Too + Large`` in ``pyramid.httpexceptions``. See + https://github.com/Pylons/pyramid/pull/1372/files - ``pcreate`` when run without a scaffold argument will now print information - on the missing flag, as well as a list of available scaffolds. See + on the missing flag, as well as a list of available scaffolds. See https://github.com/Pylons/pyramid/pull/1566 and https://github.com/Pylons/pyramid/issues/1297 +- ``pcreate`` will now ask for confirmation if invoked with an argument for a + project name that already exists or is importable in the current environment. + See https://github.com/Pylons/pyramid/issues/1357 and + https://github.com/Pylons/pyramid/pull/1837 + - Add :func:`pyramid.request.apply_request_extensions` function which can be used in testing to apply any request extensions configured via ``config.add_request_method``. Previously it was only possible to test the - extensions by going through Pyramid's router. See + extensions by going through Pyramid's router. See https://github.com/Pylons/pyramid/pull/1581 - - Make it possible to subclass ``pyramid.request.Request`` and also use - ``pyramid.request.Request.add_request.method``. See + ``pyramid.request.Request.add_request.method``. See https://github.com/Pylons/pyramid/issues/1529 +- Additional shells for ``pshell`` can now be registered as entry points. See + https://github.com/Pylons/pyramid/pull/1891 and + https://github.com/Pylons/pyramid/pull/2012 + +- The variables injected into ``pshell`` are now displayed with their + docstrings instead of the default ``str(obj)`` when possible. See + https://github.com/Pylons/pyramid/pull/1929 + + Deprecations ------------ +- The ``pserve`` command's daemonization features, as well as + ``--monitor-restart``, have been deprecated. This includes the + ``[start,stop,restart,status]`` subcommands, as well as the ``--daemon``, + ``--stop-daemon``, ``--pid-file``, ``--status``, ``--user``, and ``--group`` + flags. See https://github.com/Pylons/pyramid/pull/2120 and + https://github.com/Pylons/pyramid/pull/2189 and + https://github.com/Pylons/pyramid/pull/1641 + + Please use a real process manager in the future instead of relying on + ``pserve`` to daemonize itself. Many options exist, including your operating + system's services, such as Systemd or Upstart, as well as Python-based + solutions like Circus and Supervisor. + + See https://github.com/Pylons/pyramid/pull/1641 and + https://github.com/Pylons/pyramid/pull/2120 + - The ``principal`` argument to :func:`pyramid.security.remember` was renamed - to ``userid``. Using ``principal`` as the argument name still works and will + to ``userid``. Using ``principal`` as the argument name still works and will continue to work for the next few releases, but a deprecation warning is printed. @@ -150,21 +202,35 @@ Scaffolding Enhancements - Added line numbers to the log formatters in the scaffolds to assist with debugging. See https://github.com/Pylons/pyramid/pull/1326 -- Update scaffold generating machinery to return the version of pyramid and - pyramid docs for use in scaffolds. Updated ``starter``, ``alchemy`` and - ``zodb`` templates to have links to correctly versioned documentation and - reflect which pyramid was used to generate the scaffold. +- Updated scaffold generating machinery to return the version of :app:`Pyramid` + and its documentation for use in scaffolds. Updated ``starter``, ``alchemy`` + and ``zodb`` templates to have links to correctly versioned documentation, + and to reflect which :app:`Pyramid` was used to generate the scaffold. + +- Removed non-ASCII copyright symbol from templates, as this was causing the + scaffolds to fail for project generation. -- Removed non-ascii copyright symbol from templates, as this was - causing the scaffolds to fail for project generation. Documentation Enhancements -------------------------- -- Removed logging configuration from Quick Tutorial ini files except for - scaffolding- and logging-related chapters to avoid needing to explain it too +- Removed logging configuration from Quick Tutorial ``ini`` files, except for + scaffolding- and logging-related chapters, to avoid needing to explain it too early. -- Improve and clarify the documentation on what Pyramid defines as a - ``principal`` and a ``userid`` in its security APIs. - See https://github.com/Pylons/pyramid/pull/1399 +- Improve and clarify the documentation on what :app:`Pyramid` defines as a + ``principal`` and a ``userid`` in its security APIs. See + https://github.com/Pylons/pyramid/pull/1399 + +- Moved the documentation for ``accept`` on + :meth:`pyramid.config.Configurator.add_view` to no longer be part of the + predicate list. See https://github.com/Pylons/pyramid/issues/1391 for a bug + report stating ``not_`` was failing on ``accept``. Discussion with @mcdonc + led to the conclusion that it should not be documented as a predicate. + See https://github.com/Pylons/pyramid/pull/1487 for this PR. + +- Clarify a previously-implied detail of the ``ISession.invalidate`` API + documentation. + +- Add documentation of command line programs (``p*`` scripts). See + https://github.com/Pylons/pyramid/pull/2191 -- cgit v1.2.3 From 8a80b1094cf0ba762b30a9bae56831d4daf69e3c Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 5 Jan 2016 04:33:29 -0800 Subject: update links to tutorials in cookbook --- docs/index.rst | 6 +++--- docs/quick_tour.rst | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/index.rst b/docs/index.rst index 8c8a0a18d..9a34f088b 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -39,9 +39,9 @@ speed right away. format, with somewhat deeper treatment of each topic and with working code. * Like learning by example? Visit the official :ref:`html_tutorials` as well as - the community-contributed :ref:`Pyramid tutorials - `, which include a :ref:`Todo List Application - in One File `. + the community-contributed :ref:`Pyramid Tutorials + ` and :ref:`Pyramid Cookbook + `. * For help getting Pyramid set up, try :ref:`installing_chapter`. diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index be5be2e36..56ca53a69 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -98,7 +98,7 @@ one that we will revisit regurlarly in this *Quick Tour*. .. seealso:: See also: :ref:`Quick Tutorial Hello World `, :ref:`firstapp_chapter`, and - :ref:`Single File Tasks tutorial ` + :ref:`Todo List Application in One File ` Handling web requests and responses =================================== -- cgit v1.2.3 From 791d5947e37a52e9d34355a9c4fc9d9f1cd359e4 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 5 Jan 2016 04:47:30 -0800 Subject: remove unused "awesome" directory from quick_tour. it had references to pylonshq.com, which no longer exists. --- docs/quick_tour/awesome/CHANGES.txt | 4 - docs/quick_tour/awesome/MANIFEST.in | 2 - docs/quick_tour/awesome/README.txt | 4 - docs/quick_tour/awesome/awesome/__init__.py | 23 ------ docs/quick_tour/awesome/awesome/locale/awesome.pot | 21 ----- .../awesome/locale/de/LC_MESSAGES/awesome.mo | Bin 460 -> 0 bytes .../awesome/locale/de/LC_MESSAGES/awesome.po | 21 ----- .../awesome/locale/fr/LC_MESSAGES/awesome.mo | Bin 461 -> 0 bytes .../awesome/locale/fr/LC_MESSAGES/awesome.po | 21 ----- docs/quick_tour/awesome/awesome/models.py | 8 -- docs/quick_tour/awesome/awesome/static/favicon.ico | Bin 1406 -> 0 bytes docs/quick_tour/awesome/awesome/static/logo.png | Bin 6641 -> 0 bytes docs/quick_tour/awesome/awesome/static/pylons.css | 73 ----------------- .../awesome/awesome/templates/mytemplate.jinja2 | 87 --------------------- docs/quick_tour/awesome/awesome/tests.py | 21 ----- docs/quick_tour/awesome/awesome/views.py | 6 -- docs/quick_tour/awesome/development.ini | 49 ------------ docs/quick_tour/awesome/message-extraction.ini | 3 - docs/quick_tour/awesome/setup.py | 36 --------- 19 files changed, 379 deletions(-) delete mode 100644 docs/quick_tour/awesome/CHANGES.txt delete mode 100644 docs/quick_tour/awesome/MANIFEST.in delete mode 100644 docs/quick_tour/awesome/README.txt delete mode 100644 docs/quick_tour/awesome/awesome/__init__.py delete mode 100644 docs/quick_tour/awesome/awesome/locale/awesome.pot delete mode 100644 docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.mo delete mode 100644 docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.po delete mode 100644 docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.mo delete mode 100644 docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.po delete mode 100644 docs/quick_tour/awesome/awesome/models.py delete mode 100644 docs/quick_tour/awesome/awesome/static/favicon.ico delete mode 100644 docs/quick_tour/awesome/awesome/static/logo.png delete mode 100644 docs/quick_tour/awesome/awesome/static/pylons.css delete mode 100644 docs/quick_tour/awesome/awesome/templates/mytemplate.jinja2 delete mode 100644 docs/quick_tour/awesome/awesome/tests.py delete mode 100644 docs/quick_tour/awesome/awesome/views.py delete mode 100644 docs/quick_tour/awesome/development.ini delete mode 100644 docs/quick_tour/awesome/message-extraction.ini delete mode 100644 docs/quick_tour/awesome/setup.py (limited to 'docs') diff --git a/docs/quick_tour/awesome/CHANGES.txt b/docs/quick_tour/awesome/CHANGES.txt deleted file mode 100644 index ffa255da8..000000000 --- a/docs/quick_tour/awesome/CHANGES.txt +++ /dev/null @@ -1,4 +0,0 @@ -0.0 ---- - -- Initial version diff --git a/docs/quick_tour/awesome/MANIFEST.in b/docs/quick_tour/awesome/MANIFEST.in deleted file mode 100644 index e78395da8..000000000 --- a/docs/quick_tour/awesome/MANIFEST.in +++ /dev/null @@ -1,2 +0,0 @@ -include *.txt *.ini *.cfg *.rst -recursive-include awesome *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.js *.html *.xml diff --git a/docs/quick_tour/awesome/README.txt b/docs/quick_tour/awesome/README.txt deleted file mode 100644 index f695286d9..000000000 --- a/docs/quick_tour/awesome/README.txt +++ /dev/null @@ -1,4 +0,0 @@ -awesome README - - - diff --git a/docs/quick_tour/awesome/awesome/__init__.py b/docs/quick_tour/awesome/awesome/__init__.py deleted file mode 100644 index 408033997..000000000 --- a/docs/quick_tour/awesome/awesome/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -from pyramid.config import Configurator -from pyramid_jinja2 import renderer_factory -from awesome.models import get_root - -def main(global_config, **settings): - """ This function returns a WSGI application. - - It is usually called by the PasteDeploy framework during - ``paster serve``. - """ - settings = dict(settings) - settings.setdefault('jinja2.i18n.domain', 'awesome') - - config = Configurator(root_factory=get_root, settings=settings) - config.add_translation_dirs('locale/') - config.include('pyramid_jinja2') - - config.add_static_view('static', 'static') - config.add_view('awesome.views.my_view', - context='awesome.models.MyModel', - renderer="mytemplate.jinja2") - - return config.make_wsgi_app() diff --git a/docs/quick_tour/awesome/awesome/locale/awesome.pot b/docs/quick_tour/awesome/awesome/locale/awesome.pot deleted file mode 100644 index 9c9460cb2..000000000 --- a/docs/quick_tour/awesome/awesome/locale/awesome.pot +++ /dev/null @@ -1,21 +0,0 @@ -# Translations template for PROJECT. -# Copyright (C) 2011 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR , 2011. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: PROJECT VERSION\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2011-05-12 09:14-0330\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 0.9.6\n" - -msgid "Hello!" -msgstr "" diff --git a/docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.mo b/docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.mo deleted file mode 100644 index 40bf0c271..000000000 Binary files a/docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.mo and /dev/null differ diff --git a/docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.po b/docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.po deleted file mode 100644 index 0df243dba..000000000 --- a/docs/quick_tour/awesome/awesome/locale/de/LC_MESSAGES/awesome.po +++ /dev/null @@ -1,21 +0,0 @@ -# Translations template for PROJECT. -# Copyright (C) 2011 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR , 2011. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: PROJECT VERSION\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2011-05-12 09:14-0330\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 0.9.6\n" - -msgid "Hello!" -msgstr "Hallo!" diff --git a/docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.mo b/docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.mo deleted file mode 100644 index 4fc438bfe..000000000 Binary files a/docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.mo and /dev/null differ diff --git a/docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.po b/docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.po deleted file mode 100644 index dc0aae5d7..000000000 --- a/docs/quick_tour/awesome/awesome/locale/fr/LC_MESSAGES/awesome.po +++ /dev/null @@ -1,21 +0,0 @@ -# Translations template for PROJECT. -# Copyright (C) 2011 ORGANIZATION -# This file is distributed under the same license as the PROJECT project. -# FIRST AUTHOR , 2011. -# -#, fuzzy -msgid "" -msgstr "" -"Project-Id-Version: PROJECT VERSION\n" -"Report-Msgid-Bugs-To: EMAIL@ADDRESS\n" -"POT-Creation-Date: 2011-05-12 09:14-0330\n" -"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n" -"Last-Translator: FULL NAME \n" -"Language-Team: LANGUAGE \n" -"MIME-Version: 1.0\n" -"Content-Type: text/plain; charset=utf-8\n" -"Content-Transfer-Encoding: 8bit\n" -"Generated-By: Babel 0.9.6\n" - -msgid "Hello!" -msgstr "Bonjour!" diff --git a/docs/quick_tour/awesome/awesome/models.py b/docs/quick_tour/awesome/awesome/models.py deleted file mode 100644 index edd361c9c..000000000 --- a/docs/quick_tour/awesome/awesome/models.py +++ /dev/null @@ -1,8 +0,0 @@ -class MyModel(object): - pass - -root = MyModel() - - -def get_root(request): - return root diff --git a/docs/quick_tour/awesome/awesome/static/favicon.ico b/docs/quick_tour/awesome/awesome/static/favicon.ico deleted file mode 100644 index 71f837c9e..000000000 Binary files a/docs/quick_tour/awesome/awesome/static/favicon.ico and /dev/null differ diff --git a/docs/quick_tour/awesome/awesome/static/logo.png b/docs/quick_tour/awesome/awesome/static/logo.png deleted file mode 100644 index 88f5d9865..000000000 Binary files a/docs/quick_tour/awesome/awesome/static/logo.png and /dev/null differ diff --git a/docs/quick_tour/awesome/awesome/static/pylons.css b/docs/quick_tour/awesome/awesome/static/pylons.css deleted file mode 100644 index 42e2e320e..000000000 --- a/docs/quick_tour/awesome/awesome/static/pylons.css +++ /dev/null @@ -1,73 +0,0 @@ -html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-size:100%;/* 16px */ -vertical-align:baseline;background:transparent;} -body{line-height:1;} -ol,ul{list-style:none;} -blockquote,q{quotes:none;} -blockquote:before,blockquote:after,q:before,q:after{content:'';content:none;} -/* remember to define focus styles! */ -:focus{outline:0;} -/* remember to highlight inserts somehow! */ -ins{text-decoration:none;} -del{text-decoration:line-through;} -/* tables still need 'cellspacing="0"' in the markup */ -table{border-collapse:collapse;border-spacing:0;} -/* restyling */ -sub{vertical-align:sub;font-size:smaller;line-height:normal;} -sup{vertical-align:super;font-size:smaller;line-height:normal;} -/* lists */ -ul,menu,dir{display:block;list-style-type:disc;margin:1em 0;padding-left:40px;} -ol{display:block;list-style-type:decimal-leading-zero;margin:1em 0;padding-left:40px;} -li{display:list-item;} -/* nested lists have no top/bottom margins */ -ul ul,ul ol,ul dir,ul menu,ul dl,ol ul,ol ol,ol dir,ol menu,ol dl,dir ul,dir ol,dir dir,dir menu,dir dl,menu ul,menu ol,menu dir,menu menu,menu dl,dl ul,dl ol,dl dir,dl menu,dl dl{margin-top:0;margin-bottom:0;} -/* 2 deep unordered lists use a circle */ -ol ul,ul ul,menu ul,dir ul,ol menu,ul menu,menu menu,dir menu,ol dir,ul dir,menu dir,dir dir{list-style-type:circle;} -/* 3 deep (or more) unordered lists use a square */ -ol ol ul,ol ul ul,ol menu ul,ol dir ul,ol ol menu,ol ul menu,ol menu menu,ol dir menu,ol ol dir,ol ul dir,ol menu dir,ol dir dir,ul ol ul,ul ul ul,ul menu ul,ul dir ul,ul ol menu,ul ul menu,ul menu menu,ul dir menu,ul ol dir,ul ul dir,ul menu dir,ul dir dir,menu ol ul,menu ul ul,menu menu ul,menu dir ul,menu ol menu,menu ul menu,menu menu menu,menu dir menu,menu ol dir,menu ul dir,menu menu dir,menu dir dir,dir ol ul,dir ul ul,dir menu ul,dir dir ul,dir ol menu,dir ul menu,dir menu menu,dir dir menu,dir ol dir,dir ul dir,dir menu dir,dir dir dir{list-style-type:square;} -.hidden{display:none;} -p{line-height:1.5em;} -h1{font-size:1.75em;/* 28px */ -line-height:1.7em;font-family:helvetica,verdana;} -h2{font-size:1.5em;/* 24px */ -line-height:1.7em;font-family:helvetica,verdana;} -h3{font-size:1.25em;/* 20px */ -line-height:1.7em;font-family:helvetica,verdana;} -h4{font-size:1em;line-height:1.7em;font-family:helvetica,verdana;} -html,body{width:100%;height:100%;} -body{margin:0;padding:0;background-color:#ffffff;position:relative;font:16px/24px "Nobile","Lucida Grande",Lucida,Verdana,sans-serif;} -a{color:#1b61d6;text-decoration:none;} -a:hover{color:#e88f00;text-decoration:underline;} -body h1, -body h2, -body h3, -body h4, -body h5, -body h6{font-family:"Nobile","Lucida Grande",Lucida,Verdana,sans-serif;font-weight:normal;color:#144fb2;font-style:normal;} -#wrap {min-height: 100%;} -#header,#footer{width:100%;color:#ffffff;height:40px;position:absolute;text-align:center;line-height:40px;overflow:hidden;font-size:12px;} -#header{background-color:#e88f00;top:0;font-size:14px;} -#footer{background-color:#000000;bottom:0;position: relative;margin-top:-40px;clear:both;} -.header,.footer{width:700px;margin-right:auto;margin-left:auto;} -.wrapper{width:100%} -#top,#bottom{width:100%;} -#top{color:#888;background-color:#eee;height:300px;border-bottom:2px solid #ddd;} -#bottom{color:#222;background-color:#ffffff;overflow:auto;padding-bottom:80px;} -.top,.bottom{width:700px;margin-right:auto;margin-left:auto;} -.top{padding-top:100px;} -.app-welcome{margin-top:25px;} -.app-name{color:#000000;font-weight:bold;} -.bottom{padding-top:50px;} -#left{width:325px;float:left;padding-right:25px;} -#right{width:325px;float:right;padding-left:25px;} -.align-left{text-align:left;} -.align-right{text-align:right;} -.align-center{text-align:center;} -ul.links{margin:0;padding:0;} -ul.links li{list-style-type:none;font-size:14px;} -form{border-style:none;} -fieldset{border-style:none;} -input{color:#222;border:1px solid #ccc;font-family:sans-serif;font-size:12px;line-height:16px;} -input[type=text]{} -input[type=submit]{background-color:#ddd;font-weight:bold;} -/*Opera Fix*/ -body:before {content:"";height:100%;float:left;width:0;margin-top:-32767px;} diff --git a/docs/quick_tour/awesome/awesome/templates/mytemplate.jinja2 b/docs/quick_tour/awesome/awesome/templates/mytemplate.jinja2 deleted file mode 100644 index 8bf676041..000000000 --- a/docs/quick_tour/awesome/awesome/templates/mytemplate.jinja2 +++ /dev/null @@ -1,87 +0,0 @@ - - - - The Pyramid Web Framework - - - - - - - - - - -
- -
-
- Logo -

- Welcome to {{project}}, an application generated by
- the Pyramid web framework. -

-
-
-
-
-

{% trans %}Hello!{% endtrans %}

-

Request performed with {{ request.locale_name }} locale.

-
-
-
-

Search Pyramid documentation

-
- - -
-
- -
-
-
- - - diff --git a/docs/quick_tour/awesome/awesome/tests.py b/docs/quick_tour/awesome/awesome/tests.py deleted file mode 100644 index ac222e25b..000000000 --- a/docs/quick_tour/awesome/awesome/tests.py +++ /dev/null @@ -1,21 +0,0 @@ -import unittest -from pyramid import testing -from pyramid.i18n import TranslationStringFactory - -_ = TranslationStringFactory('awesome') - - -class ViewTests(unittest.TestCase): - - def setUp(self): - testing.setUp() - - def tearDown(self): - testing.tearDown() - - def test_my_view(self): - from awesome.views import my_view - request = testing.DummyRequest() - response = my_view(request) - self.assertEqual(response['project'], 'awesome') - diff --git a/docs/quick_tour/awesome/awesome/views.py b/docs/quick_tour/awesome/awesome/views.py deleted file mode 100644 index 67b282f87..000000000 --- a/docs/quick_tour/awesome/awesome/views.py +++ /dev/null @@ -1,6 +0,0 @@ -from pyramid.i18n import TranslationStringFactory - -_ = TranslationStringFactory('awesome') - -def my_view(request): - return {'project':'awesome'} diff --git a/docs/quick_tour/awesome/development.ini b/docs/quick_tour/awesome/development.ini deleted file mode 100644 index a473d32f1..000000000 --- a/docs/quick_tour/awesome/development.ini +++ /dev/null @@ -1,49 +0,0 @@ -[app:awesome] -use = egg:awesome -reload_templates = true -debug_authorization = false -debug_notfound = false -debug_routematch = false -debug_templates = true -default_locale_name = en -jinja2.directories = awesome:templates - -[pipeline:main] -pipeline = - awesome - -[server:main] -use = egg:pyramid#wsgiref -host = 0.0.0.0 -port = 6543 - -# Begin logging configuration - -[loggers] -keys = root, awesome - -[handlers] -keys = console - -[formatters] -keys = generic - -[logger_root] -level = INFO -handlers = console - -[logger_awesome] -level = DEBUG -handlers = -qualname = awesome - -[handler_console] -class = StreamHandler -args = (sys.stderr,) -level = NOTSET -formatter = generic - -[formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s - -# End logging configuration diff --git a/docs/quick_tour/awesome/message-extraction.ini b/docs/quick_tour/awesome/message-extraction.ini deleted file mode 100644 index 0c3d54bc1..000000000 --- a/docs/quick_tour/awesome/message-extraction.ini +++ /dev/null @@ -1,3 +0,0 @@ -[python: **.py] -[jinja2: **.jinja2] -encoding = utf-8 diff --git a/docs/quick_tour/awesome/setup.py b/docs/quick_tour/awesome/setup.py deleted file mode 100644 index 32d666317..000000000 --- a/docs/quick_tour/awesome/setup.py +++ /dev/null @@ -1,36 +0,0 @@ -import os - -from setuptools import setup, find_packages - -here = os.path.abspath(os.path.dirname(__file__)) -README = open(os.path.join(here, 'README.txt')).read() -CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() - -requires=['pyramid>=1.0.2', 'pyramid_jinja2'] - -setup(name='awesome', - version='0.0', - description='awesome', - long_description=README + '\n\n' + CHANGES, - classifiers=[ - "Programming Language :: Python", - "Framework :: Pylons", - "Topic :: Internet :: WWW/HTTP", - "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", - ], - author='', - author_email='', - url='', - keywords='web pyramid pylons', - packages=find_packages(), - include_package_data=True, - zip_safe=False, - install_requires=requires, - tests_require=requires, - test_suite="awesome", - entry_points = """\ - [paste.app_factory] - main = awesome:main - """, - paster_plugins=['pyramid'], - ) -- cgit v1.2.3 From 6860b286dcf604eaef4940ab8e8e10e8cbcc1a58 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 8 Jan 2016 06:22:05 -0800 Subject: update glossary with cookbook rst syntax. closes #2215 --- docs/glossary.rst | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/glossary.rst b/docs/glossary.rst index 60e861597..60f03f000 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -960,10 +960,10 @@ Glossary users transition from Pylons and those preferring a more Pylons-like API. The scaffold has been retired but the demo plays a similar role. - Pyramid Cookbook - Additional documentation for Pyramid which presents topical, - practical uses of Pyramid: - http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest. + Pyramid Community Cookbook + Additional, community-based documentation for Pyramid which presents + topical, practical uses of Pyramid: + :ref:`Pyramid Community Cookbook ` distutils The standard system for packaging and distributing Python packages. See -- cgit v1.2.3 From 99098dddf8baa23727f410f2fa6b543c0641fa21 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 8 Jan 2016 06:32:19 -0800 Subject: revert glossary entry name for tox on 3.5. I'll get this on a massive update on another pass. See https://github.com/Pylons/pyramid_cookbook/issues/155 --- docs/glossary.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/glossary.rst b/docs/glossary.rst index 60f03f000..82423a59d 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -960,7 +960,7 @@ Glossary users transition from Pylons and those preferring a more Pylons-like API. The scaffold has been retired but the demo plays a similar role. - Pyramid Community Cookbook + Pyramid Cookbook Additional, community-based documentation for Pyramid which presents topical, practical uses of Pyramid: :ref:`Pyramid Community Cookbook ` -- cgit v1.2.3 From 2b80947c9b032896b917535db5cf4dbe125e75b2 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 9 Jan 2016 23:13:53 -0800 Subject: Minor grammar, rewrap to 79 columns, in Ameliorations section --- docs/designdefense.rst | 91 ++++++++++++++++++++++++-------------------------- 1 file changed, 44 insertions(+), 47 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index bfde25246..2ce9dc12c 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -175,11 +175,11 @@ Ameliorations +++++++++++++ First, the primary amelioration: :app:`Pyramid` *does not expect application -developers to understand ZCA concepts or any of its APIs*. If an -*application* developer needs to understand a ZCA concept or API during the -creation of a :app:`Pyramid` application, we've failed on some axis. +developers to understand ZCA concepts or any of its APIs*. If an *application* +developer needs to understand a ZCA concept or API during the creation of a +:app:`Pyramid` application, we've failed on some axis. -Instead, the framework hides the presence of the ZCA registry behind +Instead the framework hides the presence of the ZCA registry behind special-purpose API functions that *do* use ZCA APIs. Take for example the ``pyramid.security.authenticated_userid`` function, which returns the userid present in the current request or ``None`` if no userid is present in the @@ -191,10 +191,9 @@ current request. The application developer calls it like so: from pyramid.security import authenticated_userid userid = authenticated_userid(request) -He now has the current user id. +They now have the current user id. -Under its hood however, the implementation of ``authenticated_userid`` -is this: +Under its hood however, the implementation of ``authenticated_userid`` is this: .. code-block:: python :linenos: @@ -211,58 +210,56 @@ is this: return policy.authenticated_userid(request) Using such wrappers, we strive to always hide the ZCA API from application -developers. Application developers should just never know about the ZCA API: -they should call a Python function with some object germane to the domain as -an argument, and it should return a result. A corollary that follows is -that any reader of an application that has been written using :app:`Pyramid` -needn't understand the ZCA API either. +developers. Application developers should just never know about the ZCA API; +they should call a Python function with some object germane to the domain as an +argument, and it should return a result. A corollary that follows is that any +reader of an application that has been written using :app:`Pyramid` needn't +understand the ZCA API either. Hiding the ZCA API from application developers and code readers is a form of enhancing domain specificity. No application developer wants to need to -understand the small, detailed mechanics of how a web framework does its -thing. People want to deal in concepts that are closer to the domain they're -working in: for example, web developers want to know about *users*, not -*utilities*. :app:`Pyramid` uses the ZCA as an implementation detail, not as -a feature which is exposed to end users. +understand the small, detailed mechanics of how a web framework does its thing. +People want to deal in concepts that are closer to the domain they're working +in. For example, web developers want to know about *users*, not *utilities*. +:app:`Pyramid` uses the ZCA as an implementation detail, not as a feature which +is exposed to end users. However, unlike application developers, *framework developers*, including people who want to override :app:`Pyramid` functionality via preordained -framework plugpoints like traversal or view lookup *must* understand the ZCA +framework plugpoints like traversal or view lookup, *must* understand the ZCA registry API. :app:`Pyramid` framework developers were so concerned about conceptual load -issues of the ZCA registry API for framework developers that a `replacement -registry implementation `_ -named :mod:`repoze.component` was actually developed. Though this package -has a registry implementation which is fully functional and well-tested, and -its API is much nicer than the ZCA registry API, work on it was largely -abandoned and it is not used in :app:`Pyramid`. We continued to use a ZCA -registry within :app:`Pyramid` because it ultimately proved a better fit. +issues of the ZCA registry API that a `replacement registry implementation +`_ named :mod:`repoze.component` +was actually developed. Though this package has a registry implementation +which is fully functional and well-tested, and its API is much nicer than the +ZCA registry API, work on it was largely abandoned, and it is not used in +:app:`Pyramid`. We continued to use a ZCA registry within :app:`Pyramid` +because it ultimately proved a better fit. .. note:: - We continued using ZCA registry rather than disusing it in - favor of using the registry implementation in - :mod:`repoze.component` largely because the ZCA concept of - interfaces provides for use of an interface hierarchy, which is - useful in a lot of scenarios (such as context type inheritance). - Coming up with a marker type that was something like an interface - that allowed for this functionality seemed like it was just - reinventing the wheel. - -Making framework developers and extenders understand the ZCA registry API is -a trade-off. We (the :app:`Pyramid` developers) like the features that the -ZCA registry gives us, and we have long-ago borne the weight of understanding -what it does and how it works. The authors of :app:`Pyramid` understand the -ZCA deeply and can read code that uses it as easily as any other code. + We continued using ZCA registry rather than disusing it in favor of using + the registry implementation in :mod:`repoze.component` largely because the + ZCA concept of interfaces provides for use of an interface hierarchy, which + is useful in a lot of scenarios (such as context type inheritance). Coming + up with a marker type that was something like an interface that allowed for + this functionality seemed like it was just reinventing the wheel. + +Making framework developers and extenders understand the ZCA registry API is a +trade-off. We (the :app:`Pyramid` developers) like the features that the ZCA +registry gives us, and we have long-ago borne the weight of understanding what +it does and how it works. The authors of :app:`Pyramid` understand the ZCA +deeply and can read code that uses it as easily as any other code. But we recognize that developers who might want to extend the framework are not -as comfortable with the ZCA registry API as the original developers are with -it. So, for the purposes of being kind to third-party :app:`Pyramid` -framework developers in, we've drawn some lines in the sand. +as comfortable with the ZCA registry API as the original developers. So for +the purpose of being kind to third-party :app:`Pyramid` framework developers, +we've drawn some lines in the sand. -In all core code, We've made use of ZCA global API functions such as -``zope.component.getUtility`` and ``zope.component.getAdapter`` the exception +In all core code, we've made use of ZCA global API functions, such as +``zope.component.getUtility`` and ``zope.component.getAdapter``, the exception instead of the rule. So instead of: .. code-block:: python @@ -282,9 +279,9 @@ instead of the rule. So instead of: registry = get_current_registry() policy = registry.getUtility(IAuthenticationPolicy) -While the latter is more verbose, it also arguably makes it more obvious -what's going on. All of the :app:`Pyramid` core code uses this pattern -rather than the ZCA global API. +While the latter is more verbose, it also arguably makes it more obvious what's +going on. All of the :app:`Pyramid` core code uses this pattern rather than +the ZCA global API. Rationale +++++++++ -- cgit v1.2.3 From 1f7305442e2aa824af4223df6b844cc988034492 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 13 Jan 2016 09:22:50 -0800 Subject: add python 3.5 --- docs/narr/install.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/narr/install.rst b/docs/narr/install.rst index 26d458727..164442262 100644 --- a/docs/narr/install.rst +++ b/docs/narr/install.rst @@ -15,8 +15,8 @@ You will need `Python `_ version 2.6 or better to run .. sidebar:: Python Versions As of this writing, :app:`Pyramid` has been tested under Python 2.6, Python - 2.7, Python 3.2, Python 3.3, Python 3.4, PyPy, and PyPy3. :app:`Pyramid` - does not run under any version of Python before 2.6. + 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, PyPy, and PyPy3. + :app:`Pyramid` does not run under any version of Python before 2.6. :app:`Pyramid` is known to run on all popular UNIX-like systems such as Linux, Mac OS X, and FreeBSD as well as on Windows platforms. It is also known to run -- cgit v1.2.3 From 384007c4e6e1c0c397b9c643c8c34bdf0ddf4b07 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 13 Jan 2016 13:24:26 -0800 Subject: update for python 3.5 --- docs/narr/install.rst | 2 +- docs/narr/introduction.rst | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'docs') diff --git a/docs/narr/install.rst b/docs/narr/install.rst index 164442262..381e325df 100644 --- a/docs/narr/install.rst +++ b/docs/narr/install.rst @@ -46,7 +46,7 @@ Alternatively, you can use the `homebrew `_ package manager. # for python 2.7 $ brew install python - # for python 3.4 + # for python 3.5 $ brew install python3 If you use an installer for your Python, then you can skip to the section diff --git a/docs/narr/introduction.rst b/docs/narr/introduction.rst index 7906dd85d..40f465b0a 100644 --- a/docs/narr/introduction.rst +++ b/docs/narr/introduction.rst @@ -861,10 +861,10 @@ tests, as measured by the ``coverage`` tool available on PyPI. It also has greater than 95% decision/condition coverage as measured by the ``instrumental`` tool available on PyPI. It is automatically tested by the Jenkins tool on Python 2.6, Python 2.7, Python 3.2, Python 3.3, Python 3.4, -PyPy, and PyPy3 after each commit to its GitHub repository. Official Pyramid -add-ons are held to a similar testing standard. We still find bugs in Pyramid -and its official add-ons, but we've noticed we find a lot more of them while -working on other projects that don't have a good testing regime. +Python 3.5, PyPy, and PyPy3 after each commit to its GitHub repository. +Official Pyramid add-ons are held to a similar testing standard. We still find +bugs in Pyramid and its official add-ons, but we've noticed we find a lot more +of them while working on other projects that don't have a good testing regime. Example: http://jenkins.pylonsproject.org/ -- cgit v1.2.3 From 34515f33b3e391dd1c0c727bf5ef4af586b57889 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Thu, 14 Jan 2016 02:55:04 -0800 Subject: Rename Cookbook to Pyramid Community Cookbook - use .rst intersphinx labels for pages instead of broken URLs --- docs/glossary.rst | 2 +- docs/index.rst | 2 +- docs/narr/advconfig.rst | 7 +++---- docs/narr/i18n.rst | 6 +++--- docs/narr/introduction.rst | 3 +-- docs/whatsnew-1.3.rst | 9 +++++---- 6 files changed, 14 insertions(+), 15 deletions(-) (limited to 'docs') diff --git a/docs/glossary.rst b/docs/glossary.rst index 82423a59d..60f03f000 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -960,7 +960,7 @@ Glossary users transition from Pylons and those preferring a more Pylons-like API. The scaffold has been retired but the demo plays a similar role. - Pyramid Cookbook + Pyramid Community Cookbook Additional, community-based documentation for Pyramid which presents topical, practical uses of Pyramid: :ref:`Pyramid Community Cookbook ` diff --git a/docs/index.rst b/docs/index.rst index 9a34f088b..ba6ca1e49 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -40,7 +40,7 @@ speed right away. * Like learning by example? Visit the official :ref:`html_tutorials` as well as the community-contributed :ref:`Pyramid Tutorials - ` and :ref:`Pyramid Cookbook + ` and :ref:`Pyramid Community Cookbook `. * For help getting Pyramid set up, try :ref:`installing_chapter`. diff --git a/docs/narr/advconfig.rst b/docs/narr/advconfig.rst index ba9bd1352..bdcdf45a4 100644 --- a/docs/narr/advconfig.rst +++ b/docs/narr/advconfig.rst @@ -417,7 +417,6 @@ added in configuration execution order. More Information ---------------- -For more information, see the article `"A Whirlwind Tour of Advanced -Configuration Tactics" -`_ -in the Pyramid Cookbook. +For more information, see the article :ref:`A Whirlwind Tour of Advanced +Configuration Tactics ` in the Pyramid Community +Cookbook. diff --git a/docs/narr/i18n.rst b/docs/narr/i18n.rst index bb0bbe511..ecc48aa2b 100644 --- a/docs/narr/i18n.rst +++ b/docs/narr/i18n.rst @@ -666,9 +666,9 @@ can always use the more manual translation facility described in Mako Pyramid i18n Support ------------------------- -There exists a recipe within the :term:`Pyramid Cookbook` named ":ref:`Mako -Internationalization `" which explains how to add idiomatic -i18n support to :term:`Mako` templates. +There exists a recipe within the :term:`Pyramid Community Cookbook` named +:ref:`Mako Internationalization ` which explains how to add +idiomatic i18n support to :term:`Mako` templates. .. index:: single: localization deployment settings diff --git a/docs/narr/introduction.rst b/docs/narr/introduction.rst index 40f465b0a..422db557e 100644 --- a/docs/narr/introduction.rst +++ b/docs/narr/introduction.rst @@ -892,8 +892,7 @@ also maintain a "cookbook" of recipes, which are usually demonstrations of common integration scenarios too specific to add to the official narrative docs. In any case, the Pyramid documentation is comprehensive. -Example: The Pyramid Cookbook at -http://docs.pylonsproject.org/projects/pyramid-cookbook/en/latest/. +Example: The :ref:`Pyramid Community Cookbook `. .. index:: single: Pylons Project diff --git a/docs/whatsnew-1.3.rst b/docs/whatsnew-1.3.rst index 1a299e126..dd3e1b8dd 100644 --- a/docs/whatsnew-1.3.rst +++ b/docs/whatsnew-1.3.rst @@ -523,10 +523,11 @@ Documentation Enhancements :ref:`making_a_console_script`. - Removed the "Running Pyramid on Google App Engine" tutorial from the main - docs. It survives on in the Cookbook - (http://docs.pylonsproject.org/projects/pyramid_cookbook/en/latest/deployment/gae.html). - Rationale: it provides the correct info for the Python 2.5 version of GAE - only, and this version of Pyramid does not support Python 2.5. + docs. It survives on in the Pyramid Community Cookbook as + :ref:`Pyramid on Google's App Engine (using appengine-monkey) + `. Rationale: it provides the correct info for + the Python 2.5 version of GAE only, and this version of Pyramid does not + support Python 2.5. - Updated the :ref:`changing_the_forbidden_view` section, replacing explanations of registering a view using ``add_view`` or ``view_config`` -- cgit v1.2.3 From 1d837417cff0b3e8be066252213952316edf6681 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 15 Jan 2016 23:58:29 -0800 Subject: minor grammar, rewrap 79 columns, up through traversal/url dispatch debate --- docs/designdefense.rst | 97 +++++++++++++++++++++++++------------------------- 1 file changed, 49 insertions(+), 48 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 2ce9dc12c..35de8cb03 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -306,13 +306,12 @@ the ZCA registry: view that is only found when the context is some class of object, or when the context implements some :term:`interface`. -- Singularity. There's only one place where "application configuration" - lives in a :app:`Pyramid` application: in a component registry. The - component registry answers questions made to it by the framework at runtime - based on the configuration of *an application*. Note: "an application" is - not the same as "a process", multiple independently configured copies of - the same :app:`Pyramid` application are capable of running in the same - process space. +- Singularity. There's only one place where "application configuration" lives + in a :app:`Pyramid` application: in a component registry. The component + registry answers questions made to it by the framework at runtime based on + the configuration of *an application*. Note: "an application" is not the + same as "a process"; multiple independently configured copies of the same + :app:`Pyramid` application are capable of running in the same process space. - Composability. A ZCA component registry can be populated imperatively, or there's an existing mechanism to populate a registry via the use of a @@ -330,10 +329,9 @@ the ZCA registry: (non-Zope) frameworks. - Testability. Judicious use of the ZCA registry in framework code makes - testing that code slightly easier. Instead of using monkeypatching or - other facilities to register mock objects for testing, we inject - dependencies via ZCA registrations and then use lookups in the code find - our mock objects. + testing that code slightly easier. Instead of using monkeypatching or other + facilities to register mock objects for testing, we inject dependencies via + ZCA registrations, then use lookups in the code to find our mock objects. - Speed. The ZCA registry is very fast for a specific set of complex lookup scenarios that :app:`Pyramid` uses, having been optimized through the years @@ -347,17 +345,17 @@ Conclusion ++++++++++ If you only *develop applications* using :app:`Pyramid`, there's not much to -complain about here. You just should never need to understand the ZCA -registry API: use documented :app:`Pyramid` APIs instead. However, you may -be an application developer who doesn't read API documentation because it's -unmanly. Instead you read the raw source code, and because you haven't read -the documentation, you don't know what functions, classes, and methods even -*form* the :app:`Pyramid` API. As a result, you've now written code that -uses internals and you've painted yourself into a conceptual corner as a -result of needing to wrestle with some ZCA-using implementation detail. If -this is you, it's extremely hard to have a lot of sympathy for you. You'll -either need to get familiar with how we're using the ZCA registry or you'll -need to use only the documented APIs; that's why we document them as APIs. +complain about here. You just should never need to understand the ZCA registry +API; use documented :app:`Pyramid` APIs instead. However, you may be an +application developer who doesn't read API documentation. Instead you +read the raw source code, and because you haven't read the API documentation, +you don't know what functions, classes, and methods even *form* the +:app:`Pyramid` API. As a result, you've now written code that uses internals, +and you've painted yourself into a conceptual corner, needing to wrestle with +some ZCA-using implementation detail. If this is you, it's extremely hard to +have a lot of sympathy for you. You'll either need to get familiar with how +we're using the ZCA registry or you'll need to use only the documented APIs; +that's why we document them as APIs. If you *extend* or *develop* :app:`Pyramid` (create new directives, use some of the more obscure hooks as described in :ref:`hooks_chapter`, or work on @@ -366,6 +364,7 @@ at least some ZCA concepts. In some places it's used unabashedly, and will be forever. We know it's quirky, but it's also useful and fundamentally understandable if you take the time to do some reading about it. + .. _zcml_encouragement: Pyramid "Encourages Use of ZCML" @@ -381,15 +380,16 @@ completely optional. No ZCML is required at all to use :app:`Pyramid`, nor any other sort of frameworky declarative frontend to application configuration. -Pyramid Does Traversal, And I Don't Like Traversal + +Pyramid Does Traversal, and I Don't Like Traversal -------------------------------------------------- In :app:`Pyramid`, :term:`traversal` is the act of resolving a URL path to a -:term:`resource` object in a resource tree. Some people are uncomfortable -with this notion, and believe it is wrong. Thankfully, if you use -:app:`Pyramid`, and you don't want to model your application in terms of a -resource tree, you needn't use it at all. Instead, use :term:`URL dispatch` -to map URL paths to views. +:term:`resource` object in a resource tree. Some people are uncomfortable with +this notion, and believe it is wrong. Thankfully if you use :app:`Pyramid` and +you don't want to model your application in terms of a resource tree, you +needn't use it at all. Instead use :term:`URL dispatch` to map URL paths to +views. The idea that some folks believe traversal is unilaterally wrong is understandable. The people who believe it is wrong almost invariably have @@ -424,7 +424,8 @@ URL pattern matching. But the point is ultimately moot. If you don't want to use traversal, you needn't. Use URL dispatch instead. -Pyramid Does URL Dispatch, And I Don't Like URL Dispatch + +Pyramid Does URL Dispatch, and I Don't Like URL Dispatch -------------------------------------------------------- In :app:`Pyramid`, :term:`url dispatch` is the act of resolving a URL path to @@ -446,31 +447,31 @@ I'll argue that URL dispatch is ultimately useful, even if you want to use traversal as well. You can actually *combine* URL dispatch and traversal in :app:`Pyramid` (see :ref:`hybrid_chapter`). One example of such a usage: if you want to emulate something like Zope 2's "Zope Management Interface" UI on -top of your object graph (or any administrative interface), you can register -a route like ``config.add_route('manage', '/manage/*traverse')`` and then -associate "management" views in your code by using the ``route_name`` -argument to a ``view`` configuration, -e.g. ``config.add_view('.some.callable', context=".some.Resource", -route_name='manage')``. If you wire things up this way someone then walks up -to for example, ``/manage/ob1/ob2``, they might be presented with a -management interface, but walking up to ``/ob1/ob2`` would present them with -the default object view. There are other tricks you can pull in these hybrid -configurations if you're clever (and maybe masochistic) too. - -Also, if you are a URL dispatch hater, if you should ever be asked to write -an application that must use some legacy relational database structure, you -might find that using URL dispatch comes in handy for one-off associations -between views and URL paths. Sometimes it's just pointless to add a node to -the object graph that effectively represents the entry point for some bit of -code. You can just use a route and be done with it. If a route matches, a -view associated with the route will be called; if no route matches, -:app:`Pyramid` falls back to using traversal. +top of your object graph (or any administrative interface), you can register a +route like ``config.add_route('manage', '/manage/*traverse')`` and then +associate "management" views in your code by using the ``route_name`` argument +to a ``view`` configuration, e.g., ``config.add_view('.some.callable', +context=".some.Resource", route_name='manage')``. If you wire things up this +way, someone then walks up to, for example, ``/manage/ob1/ob2``, they might be +presented with a management interface, but walking up to ``/ob1/ob2`` would +present them with the default object view. There are other tricks you can pull +in these hybrid configurations if you're clever (and maybe masochistic) too. + +Also, if you are a URL dispatch hater, if you should ever be asked to write an +application that must use some legacy relational database structure, you might +find that using URL dispatch comes in handy for one-off associations between +views and URL paths. Sometimes it's just pointless to add a node to the object +graph that effectively represents the entry point for some bit of code. You +can just use a route and be done with it. If a route matches, a view +associated with the route will be called. If no route matches, :app:`Pyramid` +falls back to using traversal. But the point is ultimately moot. If you use :app:`Pyramid`, and you really don't want to use URL dispatch, you needn't use it at all. Instead, use :term:`traversal` exclusively to map URL paths to views, just like you do in :term:`Zope`. + Pyramid Views Do Not Accept Arbitrary Keyword Arguments ------------------------------------------------------- -- cgit v1.2.3 From 0f451b89f7981234614c8437d002bee48d788a51 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sat, 16 Jan 2016 16:34:29 -0600 Subject: update whatsnew fixes #2211 --- docs/whatsnew-1.6.rst | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'docs') diff --git a/docs/whatsnew-1.6.rst b/docs/whatsnew-1.6.rst index bdfcf34ab..f5c307b5d 100644 --- a/docs/whatsnew-1.6.rst +++ b/docs/whatsnew-1.6.rst @@ -41,6 +41,18 @@ Backwards Incompatibilities This does not change the API of a renderer. See https://github.com/Pylons/pyramid/pull/1563 +- In an effort to combat a common issue it is now a + :class:`~pyramid.exceptions.ConfigurationError` to register a view + callable that is actually an unbound method when using the default view + mapper. As unbound methods do not exist in PY3+ possible errors are detected + by checking if the first parameter is named ``self``. For example, + `config.add_view(ViewClass.some_method, ...)` should actually be + `config.add_view(ViewClass, attr='some_method)'`. This was always an issue + in Pyramid on PY2 but the backward incompatibility is on PY3+ where you may + not use a function with the first parameter named ``self``. In this case + it looks too much like a common error and the exception will be raised. + See https://github.com/Pylons/pyramid/pull/1498 + Feature Additions ----------------- -- cgit v1.2.3 From 51573a705f7798403f7bce5ef1bc5f614d2690f5 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 17 Jan 2016 22:27:38 -0800 Subject: minor grammar, rewrap 79 columns, up through arbitrary keywords in views --- docs/designdefense.rst | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 35de8cb03..566f10015 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -477,11 +477,10 @@ Pyramid Views Do Not Accept Arbitrary Keyword Arguments Many web frameworks (Zope, TurboGears, Pylons 1.X, Django) allow for their variant of a :term:`view callable` to accept arbitrary keyword or positional -arguments, which are filled in using values present in the ``request.POST`` -or ``request.GET`` dictionaries or by values present in the route match -dictionary. For example, a Django view will accept positional arguments -which match information in an associated "urlconf" such as -``r'^polls/(?P\d+)/$``: +arguments, which are filled in using values present in the ``request.POST``, +``request.GET``, or route match dictionaries. For example, a Django view will +accept positional arguments which match information in an associated "urlconf" +such as ``r'^polls/(?P\d+)/$``: .. code-block:: python :linenos: @@ -489,8 +488,8 @@ which match information in an associated "urlconf" such as def aview(request, poll_id): return HttpResponse(poll_id) -Zope, likewise allows you to add arbitrary keyword and positional -arguments to any method of a resource object found via traversal: +Zope likewise allows you to add arbitrary keyword and positional arguments to +any method of a resource object found via traversal: .. code-block:: python :linenos: @@ -507,13 +506,13 @@ match the names of the positional and keyword arguments in the request, and the method is called (if possible) with its argument list filled with values mentioned therein. TurboGears and Pylons 1.X operate similarly. -Out of the box, :app:`Pyramid` is configured to have none of these features. -By default, :app:`Pyramid` view callables always accept only ``request`` and -no other arguments. The rationale: this argument specification matching done -aggressively can be costly, and :app:`Pyramid` has performance as one of its -main goals, so we've decided to make people, by default, obtain information -by interrogating the request object within the view callable body instead of -providing magic to do unpacking into the view argument list. +Out of the box, :app:`Pyramid` is configured to have none of these features. By +default :app:`Pyramid` view callables always accept only ``request`` and no +other arguments. The rationale is, this argument specification matching when +done aggressively can be costly, and :app:`Pyramid` has performance as one of +its main goals. Therefore we've decided to make people, by default, obtain +information by interrogating the request object within the view callable body +instead of providing magic to do unpacking into the view argument list. However, as of :app:`Pyramid` 1.0a9, user code can influence the way view callables are expected to be called, making it possible to compose a system -- cgit v1.2.3 From b53bff96bd9ae1c71937b8e3870ac7c0eff16767 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 18 Jan 2016 11:31:23 -0800 Subject: minor grammar, rewrap 79 columns, filesize counts, up through Pyramid Is Too Big --- docs/designdefense.rst | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 566f10015..c58cc5403 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -550,7 +550,7 @@ you're building a simple bespoke web application: sources using :meth:`pyramid.config.Configurator.include`. - View and subscriber registrations made using :term:`interface` objects - instead of class objects (e.g. :ref:`using_resource_interfaces`). + instead of class objects (e.g., :ref:`using_resource_interfaces`). - A declarative :term:`authorization` system. @@ -576,42 +576,41 @@ make unit testing and implementation substitutability easier. In a bespoke web application, usually there's a single canonical deployment, and therefore no possibility of multiple code forks. Extensibility is not -required; the code is just changed in-place. Security requirements are often -less granular. Using the features listed above will often be overkill for -such an application. +required; the code is just changed in place. Security requirements are often +less granular. Using the features listed above will often be overkill for such +an application. If you don't like these features, it doesn't mean you can't or shouldn't use -:app:`Pyramid`. They are all optional, and a lot of time has been spent -making sure you don't need to know about them up-front. You can build -"Pylons-1.X-style" applications using :app:`Pyramid` that are purely bespoke -by ignoring the features above. You may find these features handy later -after building a bespoke web application that suddenly becomes popular and -requires extensibility because it must be deployed in multiple locations. +:app:`Pyramid`. They are all optional, and a lot of time has been spent making +sure you don't need to know about them up front. You can build "Pylons 1.X +style" applications using :app:`Pyramid` that are purely bespoke by ignoring +the features above. You may find these features handy later after building a +bespoke web application that suddenly becomes popular and requires +extensibility because it must be deployed in multiple locations. Pyramid Is Too Big ------------------ -"The :app:`Pyramid` compressed tarball is larger than 2MB. It must be -enormous!" +"The :app:`Pyramid` compressed tarball is larger than 2MB. It must beenormous!" -No. We just ship it with docs, test code, and scaffolding. Here's a -breakdown of what's included in subdirectories of the package tree: +No. We just ship it with docs, test code, and scaffolding. Here's a breakdown +of what's included in subdirectories of the package tree: docs/ - 4.9MB + 3.6MB pyramid/tests/ - 2.0MB + 1.3MB pyramid/scaffolds/ - 460KB + 133KB pyramid/ (except for ``pyramd/tests`` and ``pyramid/scaffolds``) - 844KB + 812KB Of the approximately 34K lines of Python code in the package, the code that actually has a chance of executing during normal operation, excluding -- cgit v1.2.3 From 5cf8c3677454303bf4e1acecf4c16809edde2a75 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 18 Jan 2016 14:53:05 -0800 Subject: overhaul quick_tour from Quick project startup with scaffolds to Sessions with updated pyramid_jinja2 scaffold --- docs/quick_tour.rst | 319 +++++++++++---------- docs/quick_tour/package/MANIFEST.in | 2 +- docs/quick_tour/package/development.ini | 63 ++-- docs/quick_tour/package/hello_world/__init__.py | 14 +- docs/quick_tour/package/hello_world/init.py | 34 --- docs/quick_tour/package/hello_world/models.py | 8 - docs/quick_tour/package/hello_world/resources.py | 8 + .../quick_tour/package/hello_world/static/logo.png | Bin 6641 -> 0 bytes .../package/hello_world/static/pylons.css | 73 ----- .../package/hello_world/static/pyramid-16x16.png | Bin 0 -> 1319 bytes .../package/hello_world/static/pyramid.png | Bin 0 -> 12901 bytes .../package/hello_world/static/theme.css | 153 ++++++++++ .../hello_world/templates/mytemplate.jinja2 | 158 +++++----- docs/quick_tour/package/hello_world/views.py | 10 +- docs/quick_tour/package/setup.cfg | 28 ++ docs/quick_tour/package/setup.py | 27 +- 16 files changed, 480 insertions(+), 417 deletions(-) delete mode 100644 docs/quick_tour/package/hello_world/init.py delete mode 100644 docs/quick_tour/package/hello_world/models.py create mode 100644 docs/quick_tour/package/hello_world/resources.py delete mode 100644 docs/quick_tour/package/hello_world/static/logo.png delete mode 100644 docs/quick_tour/package/hello_world/static/pylons.css create mode 100644 docs/quick_tour/package/hello_world/static/pyramid-16x16.png create mode 100644 docs/quick_tour/package/hello_world/static/pyramid.png create mode 100644 docs/quick_tour/package/hello_world/static/theme.css create mode 100644 docs/quick_tour/package/setup.cfg (limited to 'docs') diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index 56ca53a69..82209f623 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -457,42 +457,41 @@ have much more to offer: Quick project startup with scaffolds ==================================== -So far we have done all of our *Quick Tour* as a single Python file. -No Python packages, no structure. Most Pyramid projects, though, -aren't developed this way. +So far we have done all of our *Quick Tour* as a single Python file. No Python +packages, no structure. Most Pyramid projects, though, aren't developed this +way. -To ease the process of getting started, Pyramid provides *scaffolds* -that generate sample projects from templates in Pyramid and Pyramid -add-ons. Pyramid's ``pcreate`` command can list the available scaffolds: +To ease the process of getting started, Pyramid provides *scaffolds* that +generate sample projects from templates in Pyramid and Pyramid add-ons. +Pyramid's ``pcreate`` command can list the available scaffolds: .. code-block:: bash $ pcreate --list Available scaffolds: alchemy: Pyramid SQLAlchemy project using url dispatch - pyramid_jinja2_starter: pyramid jinja2 starter project + pyramid_jinja2_starter: Pyramid Jinja2 starter project starter: Pyramid starter project zodb: Pyramid ZODB project using traversal -The ``pyramid_jinja2`` add-on gave us a scaffold that we can use. From -the parent directory of where we want our Python package to be generated, -let's use that scaffold to make our project: +The ``pyramid_jinja2`` add-on gave us a scaffold that we can use. From the +parent directory of where we want our Python package to be generated, let's use +that scaffold to make our project: .. code-block:: bash $ pcreate --scaffold pyramid_jinja2_starter hello_world -We next use the normal Python command to set up our package for -development: +We next use the normal Python command to set up our package for development: .. code-block:: bash $ cd hello_world $ python ./setup.py develop -We are moving in the direction of a full-featured Pyramid project, -with a proper setup for Python standards (packaging) and Pyramid -configuration. This includes a new way of running your application: +We are moving in the direction of a full-featured Pyramid project, with a +proper setup for Python standards (packaging) and Pyramid configuration. This +includes a new way of running your application: .. code-block:: bash @@ -508,28 +507,27 @@ Let's look at ``pserve`` and configuration in more depth. Application running with ``pserve`` =================================== -Prior to scaffolds, our project mixed a number of operational details -into our code. Why should my main code care which HTTP server I want and -what port number to run on? +Prior to scaffolds, our project mixed a number of operational details into our +code. Why should my main code care which HTTP server I want and what port +number to run on? -``pserve`` is Pyramid's application runner, separating operational -details from your code. When you install Pyramid, a small command -program called ``pserve`` is written to your ``bin`` directory. This -program is an executable Python module. It's very small, getting most -of its brains via import. +``pserve`` is Pyramid's application runner, separating operational details from +your code. When you install Pyramid, a small command program called ``pserve`` +is written to your ``bin`` directory. This program is an executable Python +module. It's very small, getting most of its brains via import. -You can run ``pserve`` with ``--help`` to see some of its options. -Doing so reveals that you can ask ``pserve`` to watch your development -files and reload the server when they change: +You can run ``pserve`` with ``--help`` to see some of its options. Doing so +reveals that you can ask ``pserve`` to watch your development files and reload +the server when they change: .. code-block:: bash $ pserve development.ini --reload -The ``pserve`` command has a number of other options and operations. -Most of the work, though, comes from your project's wiring, as -expressed in the configuration file you supply to ``pserve``. Let's -take a look at this configuration file. +The ``pserve`` command has a number of other options and operations. Most of +the work, though, comes from your project's wiring, as expressed in the +configuration file you supply to ``pserve``. Let's take a look at this +configuration file. .. seealso:: See also: :ref:`what_is_this_pserve_thing` @@ -537,21 +535,18 @@ take a look at this configuration file. Configuration with ``.ini`` files ================================= -Earlier in *Quick Tour* we first met Pyramid's configuration system. -At that point we did all configuration in Python code. For example, -the port number chosen for our HTTP server was right there in Python -code. Our scaffold has moved this decision and more into the -``development.ini`` file: +Earlier in *Quick Tour* we first met Pyramid's configuration system. At that +point we did all configuration in Python code. For example, the port number +chosen for our HTTP server was right there in Python code. Our scaffold has +moved this decision and more into the ``development.ini`` file: .. literalinclude:: quick_tour/package/development.ini :language: ini -Let's take a quick high-level look. First the ``.ini`` file is divided -into sections: - -- ``[app:hello_world]`` configures our WSGI app +Let's take a quick high-level look. First the ``.ini`` file is divided into +sections: -- ``[pipeline:main]`` sets up our WSGI "pipeline" +- ``[app:main]`` configures our WSGI app - ``[server:main]`` holds our WSGI server settings @@ -559,23 +554,23 @@ into sections: We have a few decisions made for us in this configuration: -#. *Choice of web server:* ``use = egg:pyramid#wsgiref`` tells ``pserve`` to - use the ``wsgiref`` server that is wrapped in the Pyramid package. +#. *Choice of web server:* ``use = egg:hello_world`` tells ``pserve`` to + use the ``waitress`` server. -#. *Port number:* ``port = 6543`` tells ``wsgiref`` to listen on port 6543. +#. *Port number:* ``port = 6543`` tells ``waitress`` to listen on port 6543. #. *WSGI app:* What package has our WSGI application in it? - ``use = egg:hello_world`` in the app section tells the - configuration what application to load. + ``use = egg:hello_world`` in the app section tells the configuration what + application to load. #. *Easier development by automatic template reloading:* In development mode, you shouldn't have to restart the server when editing a Jinja2 template. - ``reload_templates = true`` sets this policy, which might be different in - production. + ``pyramid.reload_templates = true`` sets this policy, which might be + different in production. -Additionally the ``development.ini`` generated by this scaffold wired -up Python's standard logging. We'll now see in the console, for example, -a log on every request that comes in, as well as traceback information. +Additionally the ``development.ini`` generated by this scaffold wired up +Python's standard logging. We'll now see in the console, for example, a log on +every request that comes in, as well as traceback information. .. seealso:: See also: :ref:`Quick Tutorial Application Configuration `, @@ -587,76 +582,77 @@ Easier development with ``debugtoolbar`` ======================================== As we introduce the basics, we also want to show how to be productive in -development and debugging. For example, we just discussed template -reloading and earlier we showed ``--reload`` for application reloading. +development and debugging. For example, we just discussed template reloading +and earlier we showed ``--reload`` for application reloading. -``pyramid_debugtoolbar`` is a popular Pyramid add-on which makes -several tools available in your browser. Adding it to your project -illustrates several points about configuration. +``pyramid_debugtoolbar`` is a popular Pyramid add-on which makes several tools +available in your browser. Adding it to your project illustrates several points +about configuration. -First change your ``setup.py`` to say: +The scaffold ``pyramid_jinja2_starter`` is already configured to include the +add-on ``pyramid_debugtoolbar`` in its ``setup.py``: .. literalinclude:: quick_tour/package/setup.py - :start-after: Start Requires - :end-before: End Requires + :language: python + :linenos: + :lineno-start: 11 + :lines: 11-16 -...and rerun your setup: +It was installed when you previously ran: .. code-block:: bash $ python ./setup.py develop -The Python package ``pyramid_debugtoolbar`` is now installed into our -environment. The package is a Pyramid add-on, which means we need to include -its configuration into our web application. We could do this with imperative -configuration, as we did above for the ``pyramid_jinja2`` add-on: +The ``pyramid_debugtoolbar`` package is a Pyramid add-on, which means we need +to include its configuration into our web application. The ``pyramid_jinja2`` +add-on already took care of this for us in its ``__init__.py``: .. literalinclude:: quick_tour/package/hello_world/__init__.py - :start-after: Start Include - :end-before: End Include + :language: python + :linenos: + :lineno-start: 16 + :lines: 19 -Now that we have a configuration file, we can use the -``pyramid.includes`` facility and place this in our -``development.ini`` instead: +And it uses the ``pyramid.includes`` facility in our ``development.ini``: .. literalinclude:: quick_tour/package/development.ini :language: ini - :start-after: Start Includes - :end-before: End Includes - -You'll now see an attractive (and -collapsible) menu in the right of your browser, providing introspective -access to debugging information. Even better, if your web application -generates an error, you will see a nice traceback on the screen. When -you want to disable this toolbar, there's no need to change code: you can -remove it from ``pyramid.includes`` in the relevant ``.ini`` -configuration file. + :linenos: + :lineno-start: 15 + :lines: 15-16 + +You'll now see a Pyramid logo on the right side of your browser window, which +when clicked opens a new window that provides introspective access to debugging +information. Even better, if your web application generates an error, you will +see a nice traceback on the screen. When you want to disable this toolbar, +there's no need to change code: you can remove it from ``pyramid.includes`` in +the relevant ``.ini`` configuration file. .. seealso:: See also: - :ref:`Quick Tutorial - pyramid_debugtoolbar ` and + :ref:`Quick Tutorial pyramid_debugtoolbar ` and :ref:`pyramid_debugtoolbar ` Unit tests and ``nose`` ======================= -Yikes! We got this far and we haven't yet discussed tests. This is -particularly egregious, as Pyramid has had a deep commitment to full test -coverage since before its release. +Yikes! We got this far and we haven't yet discussed tests. This is particularly +egregious, as Pyramid has had a deep commitment to full test coverage since +before its release. -Our ``pyramid_jinja2_starter`` scaffold generated a ``tests.py`` module -with one unit test in it. To run it, let's install the handy ``nose`` -test runner by editing ``setup.py``. While we're at it, we'll throw in -the ``coverage`` tool which yells at us for code that isn't tested: +Our ``pyramid_jinja2_starter`` scaffold generated a ``tests.py`` module with +one unit test in it. To run it, let's install the handy ``nose`` test runner by +editing ``setup.py``. While we're at it, we'll throw in the ``coverage`` tool +which yells at us for code that isn't tested. Edit line 36 so it becomes the +following: .. code-block:: python + :linenos: + :lineno-start: 36 - setup(name='hello_world', - # Some lines removed... - extras_require={ + tests_require={ 'testing': ['nose', 'coverage'], - } - ) + }, We changed ``setup.py`` which means we need to rerun ``python ./setup.py develop``. We can now run all our tests: @@ -667,124 +663,139 @@ We changed ``setup.py`` which means we need to rerun . Name Stmts Miss Cover Missing --------------------------------------------------- - hello_world 12 8 33% 11-23 - hello_world.models 5 1 80% 8 - hello_world.tests 14 0 100% - hello_world.views 4 0 100% + hello_world 11 8 27% 11-23 + hello_world.models 5 1 80% 8 + hello_world.tests 14 0 100% + hello_world.views 4 0 100% --------------------------------------------------- - TOTAL 35 9 74% + TOTAL 34 9 74% ---------------------------------------------------------------------- - Ran 1 test in 0.931s + Ran 1 test in 0.009s OK Our unit test passed. What did our test look like? .. literalinclude:: quick_tour/package/hello_world/tests.py + :linenos: -Pyramid supplies helpers for test writing, which we use in the -test setup and teardown. Our one test imports the view, -makes a dummy request, and sees if the view returns what we expected. +Pyramid supplies helpers for test writing, which we use in the test setup and +teardown. Our one test imports the view, makes a dummy request, and sees if the +view returns what we expected. .. seealso:: See also: - :ref:`Quick Tutorial Unit Testing `, - :ref:`Quick Tutorial Functional Testing `, - and + :ref:`Quick Tutorial Unit Testing `, :ref:`Quick + Tutorial Functional Testing `, and :ref:`testing_chapter` Logging ======= -It's important to know what is going on inside our web application. -In development we might need to collect some output. In production -we might need to detect situations when other people use the site. We -need *logging*. +It's important to know what is going on inside our web application. In +development we might need to collect some output. In production we might need +to detect situations when other people use the site. We need *logging*. -Fortunately Pyramid uses the normal Python approach to logging. The -scaffold generated in your ``development.ini`` has a number of lines that -configure the logging for you to some reasonable defaults. You then see -messages sent by Pyramid (for example, when a new request comes in). +Fortunately Pyramid uses the normal Python approach to logging. The scaffold +generated in your ``development.ini`` has a number of lines that configure the +logging for you to some reasonable defaults. You then see messages sent by +Pyramid (for example, when a new request comes in). -Maybe you would like to log messages in your code? In your Python -module, import and set up the logging: +Maybe you would like to log messages in your code? In your Python module, +import and set up the logging: .. literalinclude:: quick_tour/package/hello_world/views.py - :start-after: Start Logging 1 - :end-before: End Logging 1 + :language: python + :linenos: + :lineno-start: 3 + :lines: 3-4 You can now, in your code, log messages: .. literalinclude:: quick_tour/package/hello_world/views.py - :start-after: Start Logging 2 - :end-before: End Logging 2 + :language: python + :linenos: + :lineno-start: 9 + :lines: 9-10 + :emphasize-lines: 2 -This will log ``Some Message`` at a ``debug`` log level -to the application-configured logger in your ``development.ini``. What -controls that? These sections in the configuration file: +This will log ``Some Message`` at a ``debug`` log level to the +application-configured logger in your ``development.ini``. What controls that? +These emphasized sections in the configuration file: .. literalinclude:: quick_tour/package/development.ini :language: ini - :start-after: Start Sphinx Include - :end-before: End Sphinx Include + :linenos: + :lineno-start: 36 + :lines: 36-52 + :emphasize-lines: 1-2,14-17 -Our application, a package named ``hello_world``, is set up as a logger -and configured to log messages at a ``DEBUG`` or higher level. When you -visit http://localhost:6543, your console will now show:: +Our application, a package named ``hello_world``, is set up as a logger and +configured to log messages at a ``DEBUG`` or higher level. When you visit +http://localhost:6543, your console will now show:: - 2013-08-09 10:42:42,968 DEBUG [hello_world.views][MainThread] Some Message + 2016-01-18 13:55:55,040 DEBUG [hello_world.views:10][waitress] Some Message .. seealso:: See also: - :ref:`Quick Tutorial Logging ` and - :ref:`logging_chapter` + :ref:`Quick Tutorial Logging ` and :ref:`logging_chapter`. Sessions ======== -When people use your web application, they frequently perform a task -that requires semi-permanent data to be saved. For example, a shopping -cart. This is called a :term:`session`. +When people use your web application, they frequently perform a task that +requires semi-permanent data to be saved. For example, a shopping cart. This is +called a :term:`session`. -Pyramid has basic built-in support for sessions. Third party packages such as -``pyramid_redis_sessions`` provide richer session support. Or you can create -your own custom sessioning engine. Let's take a look at the -:doc:`built-in sessioning support <../narr/sessions>`. In our -``__init__.py`` we first import the kind of sessioning we want: +Pyramid has basic built-in support for sessions. Third party packages such as +``pyramid_redis_sessions`` provide richer session support. Or you can create +your own custom sessioning engine. Let's take a look at the :doc:`built-in +sessioning support <../narr/sessions>`. In our ``__init__.py`` we first import +the kind of sessioning we want: .. literalinclude:: quick_tour/package/hello_world/__init__.py - :start-after: Start Sphinx Include 1 - :end-before: End Sphinx Include 1 + :language: python + :linenos: + :lineno-start: 2 + :lines: 2-3 + :emphasize-lines: 2 .. warning:: - As noted in the session docs, this example implementation is - not intended for use in settings with security implications. + As noted in the session docs, this example implementation is not intended + for use in settings with security implications. Now make a "factory" and pass it to the :term:`configurator`'s ``session_factory`` argument: .. literalinclude:: quick_tour/package/hello_world/__init__.py - :start-after: Start Sphinx Include 2 - :end-before: End Sphinx Include 2 + :language: python + :linenos: + :lineno-start: 13 + :lines: 13-17 + :emphasize-lines: 3-5 -Pyramid's :term:`request` object now has a ``session`` attribute -that we can use in our view code: +Pyramid's :term:`request` object now has a ``session`` attribute that we can +use in our view code in ``views.py``: .. literalinclude:: quick_tour/package/hello_world/views.py - :start-after: Start Sphinx Include 1 - :end-before: End Sphinx Include 1 + :language: python + :linenos: + :lineno-start: 9 + :lines: 9-15 + :emphasize-lines: 3-7 -With this, each reload will increase the counter displayed in our -Jinja2 template: +We need to update our Jinja2 template to show counter increment in the session: .. literalinclude:: quick_tour/package/hello_world/templates/mytemplate.jinja2 :language: jinja - :start-after: Start Sphinx Include 1 - :end-before: End Sphinx Include 1 + :linenos: + :lineno-start: 40 + :lines: 40-42 + :emphasize-lines: 3 .. seealso:: See also: - :ref:`Quick Tutorial Sessions `, - :ref:`sessions_chapter`, :ref:`flash_messages`, - :ref:`session_module`, and :term:`pyramid_redis_sessions`. + :ref:`Quick Tutorial Sessions `, :ref:`sessions_chapter`, + :ref:`flash_messages`, :ref:`session_module`, and + :term:`pyramid_redis_sessions`. Databases ========= diff --git a/docs/quick_tour/package/MANIFEST.in b/docs/quick_tour/package/MANIFEST.in index 18fbd855c..1d0352f7d 100644 --- a/docs/quick_tour/package/MANIFEST.in +++ b/docs/quick_tour/package/MANIFEST.in @@ -1,2 +1,2 @@ include *.txt *.ini *.cfg *.rst -recursive-include hello_world *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.js *.html *.xml +recursive-include hello_world *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.jinja2 *.js *.html *.xml diff --git a/docs/quick_tour/package/development.ini b/docs/quick_tour/package/development.ini index a3a73e885..20f9817a9 100644 --- a/docs/quick_tour/package/development.ini +++ b/docs/quick_tour/package/development.ini @@ -1,37 +1,41 @@ -# Start Includes -[app:hello_world] -pyramid.includes = pyramid_debugtoolbar -# End Includes +### +# app configuration +# http://docs.pylonsproject.org/projects/pyramid/en/1.6-branch/narr/environment.html +### + +[app:main] use = egg:hello_world -reload_templates = true -debug_authorization = false -debug_notfound = false -debug_routematch = false -debug_templates = true -default_locale_name = en -jinja2.directories = hello_world:templates - -[pipeline:main] -pipeline = - hello_world + +pyramid.reload_templates = true +pyramid.debug_authorization = false +pyramid.debug_notfound = false +pyramid.debug_routematch = false +pyramid.debug_templates = true +pyramid.default_locale_name = en +pyramid.includes = + pyramid_debugtoolbar + +# By default, the toolbar only appears for clients from IP addresses +# '127.0.0.1' and '::1'. +# debugtoolbar.hosts = 127.0.0.1 ::1 + +### +# wsgi server configuration +### [server:main] -use = egg:pyramid#wsgiref -host = 0.0.0.0 +use = egg:waitress#main +host = 127.0.0.1 port = 6543 -# Begin logging configuration +### +# logging configuration +# http://docs.pylonsproject.org/projects/pyramid/en/1.6-branch/narr/logging.html +### -# Start Sphinx Include [loggers] keys = root, hello_world -[logger_hello_world] -level = DEBUG -handlers = -qualname = hello_world -# End Sphinx Include - [handlers] keys = console @@ -42,6 +46,11 @@ keys = generic level = INFO handlers = console +[logger_hello_world] +level = DEBUG +handlers = +qualname = hello_world + [handler_console] class = StreamHandler args = (sys.stderr,) @@ -49,6 +58,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s - -# End logging configuration +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/package/hello_world/__init__.py b/docs/quick_tour/package/hello_world/__init__.py index 4a4fbec30..97f93d5a8 100644 --- a/docs/quick_tour/package/hello_world/__init__.py +++ b/docs/quick_tour/package/hello_world/__init__.py @@ -1,10 +1,7 @@ from pyramid.config import Configurator -from pyramid_jinja2 import renderer_factory -# Start Sphinx Include 1 +from hello_world.resources import get_root from pyramid.session import SignedCookieSessionFactory -# End Sphinx Include 1 -from hello_world.models import get_root def main(global_config, **settings): """ This function returns a WSGI application. @@ -15,20 +12,15 @@ def main(global_config, **settings): settings = dict(settings) settings.setdefault('jinja2.i18n.domain', 'hello_world') - # Start Sphinx Include 2 my_session_factory = SignedCookieSessionFactory('itsaseekreet') config = Configurator(root_factory=get_root, settings=settings, session_factory=my_session_factory) - # End Sphinx Include 2 config.add_translation_dirs('locale/') - # Start Include config.include('pyramid_jinja2') - # End Include - config.add_static_view('static', 'static') config.add_view('hello_world.views.my_view', - context='hello_world.models.MyModel', - renderer="mytemplate.jinja2") + context='hello_world.resources.MyResource', + renderer="templates/mytemplate.jinja2") return config.make_wsgi_app() diff --git a/docs/quick_tour/package/hello_world/init.py b/docs/quick_tour/package/hello_world/init.py deleted file mode 100644 index 5b5f6a118..000000000 --- a/docs/quick_tour/package/hello_world/init.py +++ /dev/null @@ -1,34 +0,0 @@ -from pyramid.config import Configurator -from pyramid_jinja2 import renderer_factory -# Start Sphinx 1 -from pyramid.session import SignedCookieSessionFactory -# End Sphinx 1 - -from hello_world.models import get_root - -def main(global_config, **settings): - """ This function returns a WSGI application. - - It is usually called by the PasteDeploy framework during - ``paster serve``. - """ - settings = dict(settings) - settings.setdefault('jinja2.i18n.domain', 'hello_world') - - config = Configurator(root_factory=get_root, settings=settings) - config.add_translation_dirs('locale/') - # Start Include - config.include('pyramid_jinja2') - # End Include - - # Start Sphinx Include 2 - my_session_factory = SignedCookieSessionFactory('itsaseekreet') - config = Configurator(session_factory=my_session_factory) - # End Sphinx Include 2 - - config.add_static_view('static', 'static') - config.add_view('hello_world.views.my_view', - context='hello_world.models.MyModel', - renderer="mytemplate.jinja2") - - return config.make_wsgi_app() diff --git a/docs/quick_tour/package/hello_world/models.py b/docs/quick_tour/package/hello_world/models.py deleted file mode 100644 index edd361c9c..000000000 --- a/docs/quick_tour/package/hello_world/models.py +++ /dev/null @@ -1,8 +0,0 @@ -class MyModel(object): - pass - -root = MyModel() - - -def get_root(request): - return root diff --git a/docs/quick_tour/package/hello_world/resources.py b/docs/quick_tour/package/hello_world/resources.py new file mode 100644 index 000000000..e89c2f363 --- /dev/null +++ b/docs/quick_tour/package/hello_world/resources.py @@ -0,0 +1,8 @@ +class MyResource(object): + pass + +root = MyResource() + + +def get_root(request): + return root diff --git a/docs/quick_tour/package/hello_world/static/logo.png b/docs/quick_tour/package/hello_world/static/logo.png deleted file mode 100644 index 88f5d9865..000000000 Binary files a/docs/quick_tour/package/hello_world/static/logo.png and /dev/null differ diff --git a/docs/quick_tour/package/hello_world/static/pylons.css b/docs/quick_tour/package/hello_world/static/pylons.css deleted file mode 100644 index 42e2e320e..000000000 --- a/docs/quick_tour/package/hello_world/static/pylons.css +++ /dev/null @@ -1,73 +0,0 @@ -html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,font,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td{margin:0;padding:0;border:0;outline:0;font-size:100%;/* 16px */ -vertical-align:baseline;background:transparent;} -body{line-height:1;} -ol,ul{list-style:none;} -blockquote,q{quotes:none;} -blockquote:before,blockquote:after,q:before,q:after{content:'';content:none;} -/* remember to define focus styles! */ -:focus{outline:0;} -/* remember to highlight inserts somehow! */ -ins{text-decoration:none;} -del{text-decoration:line-through;} -/* tables still need 'cellspacing="0"' in the markup */ -table{border-collapse:collapse;border-spacing:0;} -/* restyling */ -sub{vertical-align:sub;font-size:smaller;line-height:normal;} -sup{vertical-align:super;font-size:smaller;line-height:normal;} -/* lists */ -ul,menu,dir{display:block;list-style-type:disc;margin:1em 0;padding-left:40px;} -ol{display:block;list-style-type:decimal-leading-zero;margin:1em 0;padding-left:40px;} -li{display:list-item;} -/* nested lists have no top/bottom margins */ -ul ul,ul ol,ul dir,ul menu,ul dl,ol ul,ol ol,ol dir,ol menu,ol dl,dir ul,dir ol,dir dir,dir menu,dir dl,menu ul,menu ol,menu dir,menu menu,menu dl,dl ul,dl ol,dl dir,dl menu,dl dl{margin-top:0;margin-bottom:0;} -/* 2 deep unordered lists use a circle */ -ol ul,ul ul,menu ul,dir ul,ol menu,ul menu,menu menu,dir menu,ol dir,ul dir,menu dir,dir dir{list-style-type:circle;} -/* 3 deep (or more) unordered lists use a square */ -ol ol ul,ol ul ul,ol menu ul,ol dir ul,ol ol menu,ol ul menu,ol menu menu,ol dir menu,ol ol dir,ol ul dir,ol menu dir,ol dir dir,ul ol ul,ul ul ul,ul menu ul,ul dir ul,ul ol menu,ul ul menu,ul menu menu,ul dir menu,ul ol dir,ul ul dir,ul menu dir,ul dir dir,menu ol ul,menu ul ul,menu menu ul,menu dir ul,menu ol menu,menu ul menu,menu menu menu,menu dir menu,menu ol dir,menu ul dir,menu menu dir,menu dir dir,dir ol ul,dir ul ul,dir menu ul,dir dir ul,dir ol menu,dir ul menu,dir menu menu,dir dir menu,dir ol dir,dir ul dir,dir menu dir,dir dir dir{list-style-type:square;} -.hidden{display:none;} -p{line-height:1.5em;} -h1{font-size:1.75em;/* 28px */ -line-height:1.7em;font-family:helvetica,verdana;} -h2{font-size:1.5em;/* 24px */ -line-height:1.7em;font-family:helvetica,verdana;} -h3{font-size:1.25em;/* 20px */ -line-height:1.7em;font-family:helvetica,verdana;} -h4{font-size:1em;line-height:1.7em;font-family:helvetica,verdana;} -html,body{width:100%;height:100%;} -body{margin:0;padding:0;background-color:#ffffff;position:relative;font:16px/24px "Nobile","Lucida Grande",Lucida,Verdana,sans-serif;} -a{color:#1b61d6;text-decoration:none;} -a:hover{color:#e88f00;text-decoration:underline;} -body h1, -body h2, -body h3, -body h4, -body h5, -body h6{font-family:"Nobile","Lucida Grande",Lucida,Verdana,sans-serif;font-weight:normal;color:#144fb2;font-style:normal;} -#wrap {min-height: 100%;} -#header,#footer{width:100%;color:#ffffff;height:40px;position:absolute;text-align:center;line-height:40px;overflow:hidden;font-size:12px;} -#header{background-color:#e88f00;top:0;font-size:14px;} -#footer{background-color:#000000;bottom:0;position: relative;margin-top:-40px;clear:both;} -.header,.footer{width:700px;margin-right:auto;margin-left:auto;} -.wrapper{width:100%} -#top,#bottom{width:100%;} -#top{color:#888;background-color:#eee;height:300px;border-bottom:2px solid #ddd;} -#bottom{color:#222;background-color:#ffffff;overflow:auto;padding-bottom:80px;} -.top,.bottom{width:700px;margin-right:auto;margin-left:auto;} -.top{padding-top:100px;} -.app-welcome{margin-top:25px;} -.app-name{color:#000000;font-weight:bold;} -.bottom{padding-top:50px;} -#left{width:325px;float:left;padding-right:25px;} -#right{width:325px;float:right;padding-left:25px;} -.align-left{text-align:left;} -.align-right{text-align:right;} -.align-center{text-align:center;} -ul.links{margin:0;padding:0;} -ul.links li{list-style-type:none;font-size:14px;} -form{border-style:none;} -fieldset{border-style:none;} -input{color:#222;border:1px solid #ccc;font-family:sans-serif;font-size:12px;line-height:16px;} -input[type=text]{} -input[type=submit]{background-color:#ddd;font-weight:bold;} -/*Opera Fix*/ -body:before {content:"";height:100%;float:left;width:0;margin-top:-32767px;} diff --git a/docs/quick_tour/package/hello_world/static/pyramid-16x16.png b/docs/quick_tour/package/hello_world/static/pyramid-16x16.png new file mode 100644 index 000000000..979203112 Binary files /dev/null and b/docs/quick_tour/package/hello_world/static/pyramid-16x16.png differ diff --git a/docs/quick_tour/package/hello_world/static/pyramid.png b/docs/quick_tour/package/hello_world/static/pyramid.png new file mode 100644 index 000000000..4ab837be9 Binary files /dev/null and b/docs/quick_tour/package/hello_world/static/pyramid.png differ diff --git a/docs/quick_tour/package/hello_world/static/theme.css b/docs/quick_tour/package/hello_world/static/theme.css new file mode 100644 index 000000000..e3cf3f290 --- /dev/null +++ b/docs/quick_tour/package/hello_world/static/theme.css @@ -0,0 +1,153 @@ +@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700); +body { + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-weight: 300; + color: #ffffff; + background: #bc2131; +} +h1, +h2, +h3, +h4, +h5, +h6 { + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-weight: 300; +} +p { + font-weight: 300; +} +.font-normal { + font-weight: 400; +} +.font-semi-bold { + font-weight: 600; +} +.font-bold { + font-weight: 700; +} +.starter-template { + margin-top: 250px; +} +.starter-template .content { + margin-left: 10px; +} +.starter-template .content h1 { + margin-top: 10px; + font-size: 60px; +} +.starter-template .content h1 .smaller { + font-size: 40px; + color: #f2b7bd; +} +.starter-template .content .lead { + font-size: 25px; + color: #f2b7bd; +} +.starter-template .content .lead .font-normal { + color: #ffffff; +} +.starter-template .links { + float: right; + right: 0; + margin-top: 125px; +} +.starter-template .links ul { + display: block; + padding: 0; + margin: 0; +} +.starter-template .links ul li { + list-style: none; + display: inline; + margin: 0 10px; +} +.starter-template .links ul li:first-child { + margin-left: 0; +} +.starter-template .links ul li:last-child { + margin-right: 0; +} +.starter-template .links ul li.current-version { + color: #f2b7bd; + font-weight: 400; +} +.starter-template .links ul li a { + color: #ffffff; +} +.starter-template .links ul li a:hover { + text-decoration: underline; +} +.starter-template .links ul li .icon-muted { + color: #eb8b95; + margin-right: 5px; +} +.starter-template .links ul li:hover .icon-muted { + color: #ffffff; +} +.starter-template .copyright { + margin-top: 10px; + font-size: 0.9em; + color: #f2b7bd; + text-transform: lowercase; + float: right; + right: 0; +} +@media (max-width: 1199px) { + .starter-template .content h1 { + font-size: 45px; + } + .starter-template .content h1 .smaller { + font-size: 30px; + } + .starter-template .content .lead { + font-size: 20px; + } +} +@media (max-width: 991px) { + .starter-template { + margin-top: 0; + } + .starter-template .logo { + margin: 40px auto; + } + .starter-template .content { + margin-left: 0; + text-align: center; + } + .starter-template .content h1 { + margin-bottom: 20px; + } + .starter-template .links { + float: none; + text-align: center; + margin-top: 60px; + } + .starter-template .copyright { + float: none; + text-align: center; + } +} +@media (max-width: 767px) { + .starter-template .content h1 .smaller { + font-size: 25px; + display: block; + } + .starter-template .content .lead { + font-size: 16px; + } + .starter-template .links { + margin-top: 40px; + } + .starter-template .links ul li { + display: block; + margin: 0; + } + .starter-template .links ul li .icon-muted { + display: none; + } + .starter-template .copyright { + margin-top: 20px; + } +} + diff --git a/docs/quick_tour/package/hello_world/templates/mytemplate.jinja2 b/docs/quick_tour/package/hello_world/templates/mytemplate.jinja2 index 25a28ed7a..a6089aebc 100644 --- a/docs/quick_tour/package/hello_world/templates/mytemplate.jinja2 +++ b/docs/quick_tour/package/hello_world/templates/mytemplate.jinja2 @@ -1,90 +1,72 @@ - - - - The Pyramid Web Framework - - - - - - - - - - -
- -
-
- Logo -

- Welcome to {{project}}, an application generated by
- the Pyramid Web Framework. -

-
-
-
-
-

{% trans %}Hello!{% endtrans %}

- -

Counter: {{ request.session.counter }}

- -

Request performed with {{ request.locale_name }} locale.

+ + + + + + + + + + + Starter Scaffold for Pyramid Jinja2 + + + + + + + + + + + + + +
+
+
+
+
-
-
-

Search Pyramid documentation

-
- - -
-
- -
-
-
- - +
+
+

+ Pyramid + Jinja2 scaffold +

+

+ {% trans %}Hello{% endtrans %} to {{project}}, an application generated by
the Pyramid Web Framework 1.6.

+

Counter: {{ request.session.counter }}

+
+
+
+
+ +
+
+ +
+
+
+ + + + + + + diff --git a/docs/quick_tour/package/hello_world/views.py b/docs/quick_tour/package/hello_world/views.py index 109c260ad..9f7953c8e 100644 --- a/docs/quick_tour/package/hello_world/views.py +++ b/docs/quick_tour/package/hello_world/views.py @@ -1,22 +1,16 @@ -# Start Logging 1 +from pyramid.i18n import TranslationStringFactory + import logging log = logging.getLogger(__name__) -# End Logging 1 - -from pyramid.i18n import TranslationStringFactory _ = TranslationStringFactory('hello_world') def my_view(request): - # Start Logging 2 log.debug('Some Message') - # End Logging 2 - # Start Sphinx Include 1 session = request.session if 'counter' in session: session['counter'] += 1 else: session['counter'] = 0 - # End Sphinx Include 1 return {'project': 'hello_world'} diff --git a/docs/quick_tour/package/setup.cfg b/docs/quick_tour/package/setup.cfg new file mode 100644 index 000000000..186e796fc --- /dev/null +++ b/docs/quick_tour/package/setup.cfg @@ -0,0 +1,28 @@ +[nosetests] +match = ^test +nocapture = 1 +cover-package = hello_world +with-coverage = 1 +cover-erase = 1 + +[compile_catalog] +directory = hello_world/locale +domain = hello_world +statistics = true + +[extract_messages] +add_comments = TRANSLATORS: +output_file = hello_world/locale/hello_world.pot +width = 80 +mapping_file = message-extraction.ini + +[init_catalog] +domain = hello_world +input_file = hello_world/locale/hello_world.pot +output_dir = hello_world/locale + +[update_catalog] +domain = hello_world +input_file = hello_world/locale/hello_world.pot +output_dir = hello_world/locale +previous = true diff --git a/docs/quick_tour/package/setup.py b/docs/quick_tour/package/setup.py index f118ed5fb..61ed3c406 100644 --- a/docs/quick_tour/package/setup.py +++ b/docs/quick_tour/package/setup.py @@ -3,12 +3,17 @@ import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) -README = open(os.path.join(here, 'README.txt')).read() -CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() +with open(os.path.join(here, 'README.txt')) as f: + README = f.read() +with open(os.path.join(here, 'CHANGES.txt')) as f: + CHANGES = f.read() -# Start Requires -requires = ['pyramid>=1.0.2', 'pyramid_jinja2', 'pyramid_debugtoolbar'] -# End Requires +requires = [ + 'pyramid', + 'pyramid_jinja2', + 'pyramid_debugtoolbar', + 'waitress', +] setup(name='hello_world', version='0.0', @@ -16,7 +21,7 @@ setup(name='hello_world', long_description=README + '\n\n' + CHANGES, classifiers=[ "Programming Language :: Python", - "Framework :: Pylons", + "Framework :: Pyramid", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", ], @@ -28,14 +33,12 @@ setup(name='hello_world', include_package_data=True, zip_safe=False, install_requires=requires, - tests_require=requires, + tests_require={ + 'testing': ['nose', 'coverage'], + }, test_suite="hello_world", entry_points="""\ [paste.app_factory] main = hello_world:main """, - paster_plugins=['pyramid'], - extras_require={ - 'testing': ['nose', ], - } -) \ No newline at end of file + ) -- cgit v1.2.3 From b89295d7cfc26b24719692fa96aec24a8e1bd7ad Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 19 Jan 2016 11:13:11 -0800 Subject: workaround for #2251. See also https://github.com/sphinx-doc/sphinx/issues/2253 --- docs/quick_tour/requests/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/quick_tour/requests/app.py b/docs/quick_tour/requests/app.py index 7ac81eb50..815714464 100644 --- a/docs/quick_tour/requests/app.py +++ b/docs/quick_tour/requests/app.py @@ -4,7 +4,7 @@ from pyramid.response import Response def hello_world(request): - # Some parameters from a request such as /?name=lisa + """ Some parameters from a request such as /?name=lisa """ url = request.url name = request.params.get('name', 'No Name Provided') -- cgit v1.2.3 From d49c69250b406597a4796d158cf6540469ade414 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 20 Jan 2016 00:18:41 -0800 Subject: Do not use trailing . on versionadded rst directive. It automatically adds a . --- docs/narr/hooks.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/narr/hooks.rst b/docs/narr/hooks.rst index 6aa1a99c2..7ff119b53 100644 --- a/docs/narr/hooks.rst +++ b/docs/narr/hooks.rst @@ -262,7 +262,7 @@ already constructed a :term:`configurator`, it can also be registered via the Adding Methods or Properties to a Request Object ------------------------------------------------ -.. versionadded:: 1.4. +.. versionadded:: 1.4 Since each Pyramid application can only have one :term:`request` factory, :ref:`changing the request factory ` is not that -- cgit v1.2.3 From 4064028cadc63ed1aceb14e6c88827b88b12f839 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 20 Jan 2016 00:38:09 -0800 Subject: Update docs to reflect dropping Python 3.2 support --- docs/narr/install.rst | 4 ++-- docs/narr/introduction.rst | 10 +++++----- docs/quick_tutorial/requirements.rst | 2 +- docs/tutorials/wiki/installation.rst | 4 ++-- docs/tutorials/wiki2/installation.rst | 4 ++-- docs/whatsnew-1.3.rst | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) (limited to 'docs') diff --git a/docs/narr/install.rst b/docs/narr/install.rst index 381e325df..c4e3e2c5f 100644 --- a/docs/narr/install.rst +++ b/docs/narr/install.rst @@ -15,8 +15,8 @@ You will need `Python `_ version 2.6 or better to run .. sidebar:: Python Versions As of this writing, :app:`Pyramid` has been tested under Python 2.6, Python - 2.7, Python 3.2, Python 3.3, Python 3.4, Python 3.5, PyPy, and PyPy3. - :app:`Pyramid` does not run under any version of Python before 2.6. + 2.7, Python 3.3, Python 3.4, Python 3.5, PyPy, and PyPy3. :app:`Pyramid` + does not run under any version of Python before 2.6. :app:`Pyramid` is known to run on all popular UNIX-like systems such as Linux, Mac OS X, and FreeBSD as well as on Windows platforms. It is also known to run diff --git a/docs/narr/introduction.rst b/docs/narr/introduction.rst index 422db557e..8db52dc21 100644 --- a/docs/narr/introduction.rst +++ b/docs/narr/introduction.rst @@ -860,11 +860,11 @@ Every release of Pyramid has 100% statement coverage via unit and integration tests, as measured by the ``coverage`` tool available on PyPI. It also has greater than 95% decision/condition coverage as measured by the ``instrumental`` tool available on PyPI. It is automatically tested by the -Jenkins tool on Python 2.6, Python 2.7, Python 3.2, Python 3.3, Python 3.4, -Python 3.5, PyPy, and PyPy3 after each commit to its GitHub repository. -Official Pyramid add-ons are held to a similar testing standard. We still find -bugs in Pyramid and its official add-ons, but we've noticed we find a lot more -of them while working on other projects that don't have a good testing regime. +Jenkins tool on Python 2.6, Python 2.7, Python 3.3, Python 3.4, Python 3.5, +PyPy, and PyPy3 after each commit to its GitHub repository. Official Pyramid +add-ons are held to a similar testing standard. We still find bugs in Pyramid +and its official add-ons, but we've noticed we find a lot more of them while +working on other projects that don't have a good testing regime. Example: http://jenkins.pylonsproject.org/ diff --git a/docs/quick_tutorial/requirements.rst b/docs/quick_tutorial/requirements.rst index a737ede0e..6d5a965cd 100644 --- a/docs/quick_tutorial/requirements.rst +++ b/docs/quick_tutorial/requirements.rst @@ -19,7 +19,7 @@ make an isolated environment, and setup packaging tools.) This *Quick Tutorial* is based on: -* **Python 3.3**. Pyramid fully supports Python 3.2+ and Python 2.6+. +* **Python 3.3**. Pyramid fully supports Python 3.3+ and Python 2.6+. This tutorial uses **Python 3.3** but runs fine under Python 2.7. * **pyvenv**. We believe in virtual environments. For this tutorial, diff --git a/docs/tutorials/wiki/installation.rst b/docs/tutorials/wiki/installation.rst index 20df389c6..ff5cac4c9 100644 --- a/docs/tutorials/wiki/installation.rst +++ b/docs/tutorials/wiki/installation.rst @@ -65,11 +65,11 @@ Python 2.7: c:\> c:\Python27\Scripts\virtualenv %VENV% -Python 3.2: +Python 3.3: .. code-block:: text - c:\> c:\Python32\Scripts\virtualenv %VENV% + c:\> c:\Python33\Scripts\virtualenv %VENV% Install Pyramid and tutorial dependencies into the virtual Python environment ----------------------------------------------------------------------------- diff --git a/docs/tutorials/wiki2/installation.rst b/docs/tutorials/wiki2/installation.rst index 1385ab8c7..0715805e6 100644 --- a/docs/tutorials/wiki2/installation.rst +++ b/docs/tutorials/wiki2/installation.rst @@ -65,11 +65,11 @@ Python 2.7: c:\> c:\Python27\Scripts\virtualenv %VENV% -Python 3.2: +Python 3.3: .. code-block:: text - c:\> c:\Python32\Scripts\virtualenv %VENV% + c:\> c:\Python33\Scripts\virtualenv %VENV% Install Pyramid into the virtual Python environment --------------------------------------------------- diff --git a/docs/whatsnew-1.3.rst b/docs/whatsnew-1.3.rst index dd3e1b8dd..8de69c450 100644 --- a/docs/whatsnew-1.3.rst +++ b/docs/whatsnew-1.3.rst @@ -18,7 +18,7 @@ Python 3 Compatibility .. image:: python-3.png Pyramid continues to run on Python 2, but Pyramid is now also Python 3 -compatible. To use Pyramid under Python 3, Python 3.2 or better is required. +compatible. To use Pyramid under Python 3, Python 3.3 or better is required. Many Pyramid add-ons are already Python 3 compatible. For example, ``pyramid_debugtoolbar``, ``pyramid_jinja2``, ``pyramid_exclog``, -- cgit v1.2.3 From 0e1ad7e807a0638943fe8a050da551266567cb06 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 20 Jan 2016 00:43:08 -0800 Subject: fix underline for heading --- docs/tutorials/wiki2/installation.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/tutorials/wiki2/installation.rst b/docs/tutorials/wiki2/installation.rst index 1385ab8c7..906f00cd7 100644 --- a/docs/tutorials/wiki2/installation.rst +++ b/docs/tutorials/wiki2/installation.rst @@ -392,7 +392,7 @@ page. You can read more about the purpose of the icon at application while you develop. Decisions the ``alchemy`` scaffold has made for you -================================================================= +=================================================== Creating a project using the ``alchemy`` scaffold makes the following assumptions: -- cgit v1.2.3 From 8f364675b6cd9527a482462191c18f8b3fc22d83 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Thu, 21 Jan 2016 05:09:10 -0800 Subject: minor grammar fixes. --- docs/quick_tour.rst | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'docs') diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index 82209f623..f5f28f86a 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -43,11 +43,11 @@ production support for Python 3 in October 2011). .. note:: - Why ``easy_install`` and not ``pip``? Some distributions on which Pyramid - depends upon have optional C extensions for performance. ``pip`` cannot + Why ``easy_install`` and not ``pip``? Some distributions upon which + Pyramid depends have optional C extensions for performance. ``pip`` cannot install some binary Python distributions. With ``easy_install``, Windows users are able to obtain binary Python distributions, so they get the - benefit of the C extensions without needing a C compiler. Also, there can + benefit of the C extensions without needing a C compiler. Also there can be issues when ``pip`` and ``easy_install`` are used side-by-side in the same environment, so we chose to recommend ``easy_install`` for the sake of reducing the complexity of these instructions. -- cgit v1.2.3 From 257ac062342d5b2cd18b47737cf9fb94aa528b8a Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 22 Jan 2016 00:29:38 -0800 Subject: Overhaul Quick Tour: start to "Quick project startup with scaffolds" --- docs/quick_tour.rst | 439 +++++++++++---------- docs/quick_tour/hello_world/app.py | 2 +- docs/quick_tour/jinja2/app.py | 2 +- docs/quick_tour/jinja2/views.py | 2 - docs/quick_tour/json/app.py | 4 +- docs/quick_tour/json/hello_world.jinja2 | 4 +- docs/quick_tour/json/hello_world.pt | 17 - docs/quick_tour/json/views.py | 4 +- docs/quick_tour/requests/app.py | 2 +- docs/quick_tour/routing/app.py | 2 - docs/quick_tour/routing/views.py | 2 - docs/quick_tour/static_assets/app.py | 4 +- docs/quick_tour/static_assets/hello_world.jinja2 | 2 +- docs/quick_tour/static_assets/hello_world.pt | 16 - .../static_assets/hello_world_static.jinja2 | 10 + docs/quick_tour/static_assets/views.py | 2 +- docs/quick_tour/templating/app.py | 3 +- docs/quick_tour/templating/views.py | 2 - docs/quick_tour/view_classes/app.py | 6 +- docs/quick_tour/view_classes/hello.jinja2 | 8 +- docs/quick_tour/view_classes/views.py | 2 - docs/quick_tour/views/app.py | 2 +- 22 files changed, 256 insertions(+), 281 deletions(-) delete mode 100644 docs/quick_tour/json/hello_world.pt delete mode 100644 docs/quick_tour/static_assets/hello_world.pt create mode 100644 docs/quick_tour/static_assets/hello_world_static.jinja2 (limited to 'docs') diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index f5f28f86a..220fd4bca 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -5,19 +5,20 @@ Quick Tour of Pyramid ===================== Pyramid lets you start small and finish big. This *Quick Tour* of Pyramid is -for those who want to evaluate Pyramid, whether you are new to Python -web frameworks, or a pro in a hurry. For more detailed treatment of -each topic, give the :ref:`quick_tutorial` a try. +for those who want to evaluate Pyramid, whether you are new to Python web +frameworks, or a pro in a hurry. For more detailed treatment of each topic, +give the :ref:`quick_tutorial` a try. + Installation ============ -Once you have a standard Python environment setup, getting started with -Pyramid is a breeze. Unfortunately "standard" is not so simple in Python. -For this Quick Tour, it means: `Python `_, -a `virtual environment `_ (or -`virtualenv for Python 2.7 `_), and -`setuptools `_. +Once you have a standard Python environment setup, getting started with Pyramid +is a breeze. Unfortunately "standard" is not so simple in Python. For this +Quick Tour, it means `Python `_, a `virtual +environment `_ (or `virtualenv +for Python 2.7 `_), and `setuptools +`_. As an example, for Python 3.3+ on Linux: @@ -37,9 +38,9 @@ For Windows: c:\\> env33\\Scripts\\python ez_setup.py c:\\> env33\\Scripts\\easy_install "pyramid==\ |release|\ " -Of course Pyramid runs fine on Python 2.6+, as do the examples in this -*Quick Tour*. We're just showing Python 3 a little love (Pyramid had -production support for Python 3 in October 2011). +Of course Pyramid runs fine on Python 2.6+, as do the examples in this *Quick +Tour*. We're just showing Python 3 a little love (Pyramid had production +support for Python 3 in October 2011). .. note:: @@ -54,15 +55,15 @@ production support for Python 3 in October 2011). .. seealso:: See also: :ref:`Quick Tutorial section on Requirements `, - :ref:`installing_unix`, - :ref:`Before You Install `, and - :ref:`Installing Pyramid on a Windows System ` + :ref:`installing_unix`, :ref:`Before You Install `, and + :ref:`Installing Pyramid on a Windows System `. + Hello World =========== -Microframeworks have shown that learning starts best from a very small -first step. Here's a tiny application in Pyramid: +Microframeworks have shown that learning starts best from a very small first +step. Here's a tiny application in Pyramid: .. literalinclude:: quick_tour/hello_world/app.py :linenos: @@ -79,65 +80,63 @@ World!`` message. New to Python web programming? If so, some lines in the module merit explanation: -#. *Line 10*. The ``if __name__ == '__main__':`` is Python's way of - saying "Start here when running from the command line". +#. *Line 10*. ``if __name__ == '__main__':`` is Python's way of saying "Start + here when running from the command line". -#. *Lines 11-13*. Use Pyramid's :term:`configurator` to connect - :term:`view` code to a particular URL :term:`route`. +#. *Lines 11-13*. Use Pyramid's :term:`configurator` to connect :term:`view` + code to a particular URL :term:`route`. -#. *Lines 6-7*. Implement the view code that generates the - :term:`response`. +#. *Lines 6-7*. Implement the view code that generates the :term:`response`. #. *Lines 14-16*. Publish a :term:`WSGI` app using an HTTP server. -As shown in this example, the :term:`configurator` plays a central role -in Pyramid development. Building an application from loosely-coupled -parts via :doc:`../narr/configuration` is a central idea in Pyramid, -one that we will revisit regurlarly in this *Quick Tour*. +As shown in this example, the :term:`configurator` plays a central role in +Pyramid development. Building an application from loosely-coupled parts via +:doc:`../narr/configuration` is a central idea in Pyramid, one that we will +revisit regurlarly in this *Quick Tour*. .. seealso:: See also: :ref:`Quick Tutorial Hello World `, - :ref:`firstapp_chapter`, and - :ref:`Todo List Application in One File ` + :ref:`firstapp_chapter`, and :ref:`Todo List Application in One File + `. + Handling web requests and responses =================================== -Developing for the web means processing web requests. As this is a -critical part of a web application, web developers need a robust, -mature set of software for web requests. +Developing for the web means processing web requests. As this is a critical +part of a web application, web developers need a robust, mature set of software +for web requests. -Pyramid has always fit nicely into the existing world of Python web -development (virtual environments, packaging, scaffolding, one of the first to -embrace Python 3, etc.). Pyramid turned to the well-regarded :term:`WebOb` -Python library for request and response handling. In our example above, -Pyramid hands ``hello_world`` a ``request`` that is :ref:`based on WebOb -`. +Pyramid has always fit nicely into the existing world of Python web development +(virtual environments, packaging, scaffolding, one of the first to embrace +Python 3, etc.). Pyramid turned to the well-regarded :term:`WebOb` Python +library for request and response handling. In our example above, Pyramid hands +``hello_world`` a ``request`` that is :ref:`based on WebOb `. Let's see some features of requests and responses in action: .. literalinclude:: quick_tour/requests/app.py :pyobject: hello_world -In this Pyramid view, we get the URL being visited from ``request.url``. Also, +In this Pyramid view, we get the URL being visited from ``request.url``. Also if you visited http://localhost:6543/?name=alice in a browser, the name is included in the body of the response:: URL http://localhost:6543/?name=alice with name: alice -Finally, we set the response's content type and return the Response. +Finally we set the response's content type, and return the Response. .. seealso:: See also: - :ref:`Quick Tutorial Request and Response ` - and - :ref:`webob_chapter` + :ref:`Quick Tutorial Request and Response ` and + :ref:`webob_chapter`. + Views ===== -For the examples above, the ``hello_world`` function is a "view". In -Pyramid, views are the primary way to accept web requests and return -responses. +For the examples above, the ``hello_world`` function is a "view". In Pyramid +views are the primary way to accept web requests and return responses. So far our examples place everything in one file: @@ -149,169 +148,169 @@ So far our examples place everything in one file: - the WSGI application launcher -Let's move the views out to their own ``views.py`` module and change -the ``app.py`` to scan that module, looking for decorators that set up -the views. +Let's move the views out to their own ``views.py`` module and change the +``app.py`` to scan that module, looking for decorators that set up the views. -First, our revised ``app.py``: +First our revised ``app.py``: .. literalinclude:: quick_tour/views/app.py :linenos: -We added some more routes, but we also removed the view code. -Our views and their registrations (via decorators) are now in a module -``views.py``, which is scanned via ``config.scan('views')``. +We added some more routes, but we also removed the view code. Our views and +their registrations (via decorators) are now in a module ``views.py``, which is +scanned via ``config.scan('views')``. -We now have a ``views.py`` module that is focused on handling requests -and responses: +We now have a ``views.py`` module that is focused on handling requests and +responses: .. literalinclude:: quick_tour/views/views.py :linenos: We have four views, each leading to the other. If you start at -http://localhost:6543/, you get a response with a link to the next -view. The ``hello_view`` (available at the URL ``/howdy``) has a link -to the ``redirect_view``, which issues a redirect to the final -view. - -Earlier we saw ``config.add_view`` as one way to configure a view. This -section introduces ``@view_config``. Pyramid's configuration supports -:term:`imperative configuration`, such as the ``config.add_view`` in -the previous example. You can also use :term:`declarative -configuration`, in which a Python :term:`decorator` is placed on the -line above the view. Both approaches result in the same final -configuration, thus usually it is simply a matter of taste. +http://localhost:6543/, you get a response with a link to the next view. The +``hello_view`` (available at the URL ``/howdy``) has a link to the +``redirect_view``, which issues a redirect to the final view. + +Earlier we saw ``config.add_view`` as one way to configure a view. This section +introduces ``@view_config``. Pyramid's configuration supports :term:`imperative +configuration`, such as the ``config.add_view`` in the previous example. You +can also use :term:`declarative configuration` in which a Python +:term:`decorator` is placed on the line above the view. Both approaches result +in the same final configuration, thus usually it is simply a matter of taste. .. seealso:: See also: - :ref:`Quick Tutorial Views `, - :doc:`../narr/views`, - :doc:`../narr/viewconfig`, and - :ref:`debugging_view_configuration` + :ref:`Quick Tutorial Views `, :doc:`../narr/views`, + :doc:`../narr/viewconfig`, and :ref:`debugging_view_configuration`. + Routing ======= -Writing web applications usually means sophisticated URL design. We -just saw some Pyramid machinery for requests and views. Let's look at -features that help in routing. +Writing web applications usually means sophisticated URL design. We just saw +some Pyramid machinery for requests and views. Let's look at features that help +with routing. Above we saw the basics of routing URLs to views in Pyramid: -- Your project's "setup" code registers a route name to be used when - matching part of the URL +- Your project's "setup" code registers a route name to be used when matching + part of the URL. -- Elsewhere a view is configured to be called for that route name +- Elsewhere a view is configured to be called for that route name. .. note:: - Why do this twice? Other Python web frameworks let you create a - route and associate it with a view in one step. As - illustrated in :ref:`routes_need_ordering`, multiple routes might - match the same URL pattern. Rather than provide ways to help guess, - Pyramid lets you be explicit in ordering. Pyramid also gives - facilities to avoid the problem. + Why do this twice? Other Python web frameworks let you create a route and + associate it with a view in one step. As illustrated in + :ref:`routes_need_ordering`, multiple routes might match the same URL + pattern. Rather than provide ways to help guess, Pyramid lets you be + explicit in ordering. Pyramid also gives facilities to avoid the problem. -What if we want part of the URL to be available as data in my view? This -route declaration: +What if we want part of the URL to be available as data in my view? We can use +this route declaration, for example: .. literalinclude:: quick_tour/routing/app.py - :start-after: Start Route 1 - :end-before: End Route 1 + :linenos: + :lines: 6 + :lineno-start: 6 -With this, URLs such as ``/howdy/amy/smith`` will assign ``amy`` to -``first`` and ``smith`` to ``last``. We can then use this data in our -view: +With this, URLs such as ``/howdy/amy/smith`` will assign ``amy`` to ``first`` +and ``smith`` to ``last``. We can then use this data in our view: .. literalinclude:: quick_tour/routing/views.py - :start-after: Start Route 1 - :end-before: End Route 1 + :linenos: + :lines: 5-8 + :lineno-start: 5 + :emphasize-lines: 3 -``request.matchdict`` contains values from the URL that match the -"replacement patterns" (the curly braces) in the route declaration. -This information can then be used in your view. +``request.matchdict`` contains values from the URL that match the "replacement +patterns" (the curly braces) in the route declaration. This information can +then be used in your view. .. seealso:: See also: - :ref:`Quick Tutorial Routing `, - :doc:`../narr/urldispatch`, - :ref:`debug_routematch_section`, and - :doc:`../narr/router` + :ref:`Quick Tutorial Routing `, :doc:`../narr/urldispatch`, + :ref:`debug_routematch_section`, and :doc:`../narr/router`. + Templating ========== -Ouch. We have been making our own ``Response`` and filling the response -body with HTML. You usually won't embed an HTML string directly in -Python, but instead, will use a templating language. +Ouch. We have been making our own ``Response`` and filling the response body +with HTML. You usually won't embed an HTML string directly in Python, but +instead you will use a templating language. -Pyramid doesn't mandate a particular database system, form library, -etc. It encourages replaceability. This applies equally to templating, -which is fortunate: developers have strong views about template -languages. That said, the Pylons Project officially supports bindings for -Chameleon, Jinja2, and Mako, so in this step, let's use Chameleon. +Pyramid doesn't mandate a particular database system, form library, and so on. +It encourages replaceability. This applies equally to templating, which is +fortunate: developers have strong views about template languages. That said, +the Pylons Project officially supports bindings for Chameleon, Jinja2, and +Mako. In this step let's use Chameleon. Let's add ``pyramid_chameleon``, a Pyramid :term:`add-on` which enables -Chameleon as a :term:`renderer` in our Pyramid applications: +Chameleon as a :term:`renderer` in our Pyramid application: .. code-block:: bash $ easy_install pyramid_chameleon -With the package installed, we can include the template bindings into -our configuration: +With the package installed, we can include the template bindings into our +configuration in ``app.py``: -.. code-block:: python +.. literalinclude:: quick_tour/templating/app.py + :linenos: + :lines: 6-8 + :lineno-start: 6 + :emphasize-lines: 2 - config.include('pyramid_chameleon') - -Now lets change our views.py file: +Now lets change our ``views.py`` file: .. literalinclude:: quick_tour/templating/views.py - :start-after: Start View 1 - :end-before: End View 1 + :linenos: + :emphasize-lines: 4,6 -Ahh, that looks better. We have a view that is focused on Python code. -Our ``@view_config`` decorator specifies a :term:`renderer` that points -to our template file. Our view then simply returns data which is then -supplied to our template: +Ahh, that looks better. We have a view that is focused on Python code. Our +``@view_config`` decorator specifies a :term:`renderer` that points to our +template file. Our view then simply returns data which is then supplied to our +template ``hello_world.pt``: .. literalinclude:: quick_tour/templating/hello_world.pt :language: html -Since our view returned ``dict(name=request.matchdict['name'])``, -we can use ``name`` as a variable in our template via -``${name}``. +Since our view returned ``dict(name=request.matchdict['name'])``, we can use +``name`` as a variable in our template via ``${name}``. .. seealso:: See also: :ref:`Quick Tutorial Templating `, - :doc:`../narr/templates`, - :ref:`debugging_templates`, and - :ref:`available_template_system_bindings` + :doc:`../narr/templates`, :ref:`debugging_templates`, and + :ref:`available_template_system_bindings`. -Templating with ``jinja2`` -========================== -We just said Pyramid doesn't prefer one templating language over -another. Time to prove it. Jinja2 is a popular templating system, -modeled after Django's templates. Let's add ``pyramid_jinja2``, -a Pyramid :term:`add-on` which enables Jinja2 as a :term:`renderer` in -our Pyramid applications: +Templating with Jinja2 +====================== + +We just said Pyramid doesn't prefer one templating language over another. Time +to prove it. Jinja2 is a popular templating system, modeled after Django's +templates. Let's add ``pyramid_jinja2``, a Pyramid :term:`add-on` which enables +Jinja2 as a :term:`renderer` in our Pyramid applications: .. code-block:: bash $ easy_install pyramid_jinja2 -With the package installed, we can include the template bindings into -our configuration: - -.. code-block:: python +With the package installed, we can include the template bindings into our +configuration: - config.include('pyramid_jinja2') +.. literalinclude:: quick_tour/jinja2/app.py + :linenos: + :lines: 6-8 + :lineno-start: 6 + :emphasize-lines: 2 The only change in our view is to point the renderer at the ``.jinja2`` file: .. literalinclude:: quick_tour/jinja2/views.py - :start-after: Start View 1 - :end-before: End View 1 + :linenos: + :lines: 4-6 + :lineno-start: 4 + :emphasize-lines: 1 Our Jinja2 template is very similar to our previous template: @@ -319,54 +318,60 @@ Our Jinja2 template is very similar to our previous template: :language: html Pyramid's templating add-ons register a new kind of renderer into your -application. The renderer registration maps to different kinds of -filename extensions. In this case, changing the extension from ``.pt`` -to ``.jinja2`` passed the view response through the ``pyramid_jinja2`` -renderer. +application. The renderer registration maps to different kinds of filename +extensions. In this case, changing the extension from ``.pt`` to ``.jinja2`` +passed the view response through the ``pyramid_jinja2`` renderer. .. seealso:: See also: - :ref:`Quick Tutorial Jinja2 `, - `Jinja2 homepage `_, and - :ref:`pyramid_jinja2 Overview ` + :ref:`Quick Tutorial Jinja2 `, `Jinja2 homepage + `_, and :ref:`pyramid_jinja2 Overview + `. + Static assets ============= -Of course the Web is more than just markup. You need static assets: -CSS, JS, and images. Let's point our web app at a directory where -Pyramid will serve some static assets. First another call to the +Of course the Web is more than just markup. You need static assets: CSS, JS, +and images. Let's point our web app at a directory from which Pyramid will +serve some static assets. First let's make another call to the :term:`configurator`: .. literalinclude:: quick_tour/static_assets/app.py - :start-after: Start Static 1 - :end-before: End Static 1 + :linenos: + :lines: 6-8 + :lineno-start: 6 + :emphasize-lines: 2 This tells our WSGI application to map requests under -http://localhost:6543/static/ to files and directories inside a -``static`` directory alongside our Python module. +http://localhost:6543/static/ to files and directories inside a ``static`` +directory alongside our Python module. Next make a directory named ``static``, and place ``app.css`` inside: .. literalinclude:: quick_tour/static_assets/static/app.css :language: css -All we need to do now is point to it in the ```` of our Jinja2 -template: +All we need to do now is point to it in the ```` of our Jinja2 template, +``hello_world.jinja2``: -.. literalinclude:: quick_tour/static_assets/hello_world.pt - :language: html - :start-after: Start Link 1 - :end-before: End Link 1 +.. literalinclude:: quick_tour/static_assets/hello_world.jinja2 + :language: jinja + :linenos: + :lines: 4-6 + :lineno-start: 4 + :emphasize-lines: 2 -This link presumes that our CSS is at a URL starting with ``/static/``. -What if the site is later moved under ``/somesite/static/``? Or perhaps -a web developer changes the arrangement on disk? Pyramid provides a helper -to allow flexibility on URL generation: +This link presumes that our CSS is at a URL starting with ``/static/``. What if +the site is later moved under ``/somesite/static/``? Or perhaps a web developer +changes the arrangement on disk? Pyramid provides a helper to allow flexibility +on URL generation: -.. literalinclude:: quick_tour/static_assets/hello_world.pt - :language: html - :start-after: Start Link 2 - :end-before: End Link 2 +.. literalinclude:: quick_tour/static_assets/hello_world_static.jinja2 + :language: jinja + :linenos: + :lines: 4-6 + :lineno-start: 4 + :emphasize-lines: 2 By using ``request.static_url`` to generate the full URL to the static assets, you both ensure you stay in sync with the configuration and @@ -374,38 +379,48 @@ gain refactoring flexibility later. .. seealso:: See also: :ref:`Quick Tutorial Static Assets `, - :doc:`../narr/assets`, - :ref:`preventing_http_caching`, and - :ref:`influencing_http_caching` + :doc:`../narr/assets`, :ref:`preventing_http_caching`, and + :ref:`influencing_http_caching`. + Returning JSON ============== -Modern web apps are more than rendered HTML. Dynamic pages now use -JavaScript to update the UI in the browser by requesting server data as -JSON. Pyramid supports this with a JSON renderer: +Modern web apps are more than rendered HTML. Dynamic pages now use JavaScript +to update the UI in the browser by requesting server data as JSON. Pyramid +supports this with a JSON renderer: .. literalinclude:: quick_tour/json/views.py - :start-after: Start View 1 - :end-before: End View 2 + :linenos: + :lines: 9- + :lineno-start: 9 + +This wires up a view that returns some data through the JSON :term:`renderer`, +which calls Python's JSON support to serialize the data into JSON, and sets the +appropriate HTTP headers. + +We also need to add a route to ``app.py`` so that our app will know how to +respond to a request for ``hello.json``. -This wires up a view that returns some data through the JSON -:term:`renderer`, which calls Python's JSON support to serialize the data -into JSON and set the appropriate HTTP headers. +.. literalinclude:: quick_tour/json/app.py + :linenos: + :lines: 6-8 + :lineno-start: 6 + :emphasize-lines: 2 .. seealso:: See also: - :ref:`Quick Tutorial JSON `, - :ref:`views_which_use_a_renderer`, - :ref:`json_renderer`, and - :ref:`adding_and_overriding_renderers` + :ref:`Quick Tutorial JSON `, :ref:`views_which_use_a_renderer`, + :ref:`json_renderer`, and :ref:`adding_and_overriding_renderers`. + View classes ============ -So far our views have been simple, free-standing functions. Many times -your views are related: different ways to look at or work on the same -data, or a REST API that handles multiple operations. Grouping these -together as a :ref:`view class ` makes sense. +So far our views have been simple, free-standing functions. Many times your +views are related. They may have different ways to look at or work on the same +data, or they may be a REST API that handles multiple operations. Grouping +these together as a :ref:`view class ` makes sense and achieves +the following goals. - Group views @@ -413,46 +428,46 @@ together as a :ref:`view class ` makes sense. - Share some state and helpers -The following shows a "Hello World" example with three operations: view -a form, save a change, or press the delete button: +The following shows a "Hello World" example with three operations: view a form, +save a change, or press the delete button in our ``views.py``: .. literalinclude:: quick_tour/view_classes/views.py - :start-after: Start View 1 - :end-before: End View 1 + :linenos: + :lines: 7- + :lineno-start: 7 -As you can see, the three views are logically grouped together. -Specifically: +As you can see, the three views are logically grouped together. Specifically: -- The first view is returned when you go to ``/howdy/amy``. This URL is - mapped to the ``hello`` route that we centrally set using the optional +- The first view is returned when you go to ``/howdy/amy``. This URL is mapped + to the ``hello`` route that we centrally set using the optional ``@view_defaults``. - The second view is returned when the form data contains a field with - ``form.edit``, such as clicking on - ````. This rule - is specified in the ``@view_config`` for that view. + ``form.edit``, such as clicking on ````. This rule is specified in the ``@view_config`` for that + view. -- The third view is returned when clicking on a button such - as ````. +- The third view is returned when clicking on a button such as ````. -Only one route is needed, stated in one place atop the view class. Also, -the assignment of ``name`` is done in the ``__init__`` function. Our -templates can then use ``{{ view.name }}``. +Only one route is needed, stated in one place atop the view class. Also, the +assignment of ``name`` is done in the ``__init__`` function. Our templates can +then use ``{{ view.name }}``. -Pyramid view classes, combined with built-in and custom predicates, -have much more to offer: +Pyramid view classes, combined with built-in and custom predicates, have much +more to offer: - All the same view configuration parameters as function views -- One route leading to multiple views, based on information in the - request or data such as ``request_param``, ``request_method``, - ``accept``, ``header``, ``xhr``, ``containment``, and - ``custom_predicates`` +- One route leading to multiple views, based on information in the request or + data such as ``request_param``, ``request_method``, ``accept``, ``header``, + ``xhr``, ``containment``, and ``custom_predicates`` .. seealso:: See also: - :ref:`Quick Tutorial View Classes `, - :ref:`Quick Tutorial More View Classes `, and - :ref:`class_as_view` + :ref:`Quick Tutorial View Classes `, :ref:`Quick + Tutorial More View Classes `, and + :ref:`class_as_view`. + Quick project startup with scaffolds ==================================== diff --git a/docs/quick_tour/hello_world/app.py b/docs/quick_tour/hello_world/app.py index df5a6cf18..75d22ac96 100644 --- a/docs/quick_tour/hello_world/app.py +++ b/docs/quick_tour/hello_world/app.py @@ -13,4 +13,4 @@ if __name__ == '__main__': config.add_view(hello_world, route_name='hello') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/jinja2/app.py b/docs/quick_tour/jinja2/app.py index 83af219db..b7632807b 100644 --- a/docs/quick_tour/jinja2/app.py +++ b/docs/quick_tour/jinja2/app.py @@ -8,4 +8,4 @@ if __name__ == '__main__': config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/jinja2/views.py b/docs/quick_tour/jinja2/views.py index 916cdc720..7dbb45287 100644 --- a/docs/quick_tour/jinja2/views.py +++ b/docs/quick_tour/jinja2/views.py @@ -1,8 +1,6 @@ from pyramid.view import view_config -# Start View 1 @view_config(route_name='hello', renderer='hello_world.jinja2') -# End View 1 def hello_world(request): return dict(name=request.matchdict['name']) diff --git a/docs/quick_tour/json/app.py b/docs/quick_tour/json/app.py index 950cb478f..40faddd00 100644 --- a/docs/quick_tour/json/app.py +++ b/docs/quick_tour/json/app.py @@ -1,8 +1,6 @@ from wsgiref.simple_server import make_server - from pyramid.config import Configurator - if __name__ == '__main__': config = Configurator() config.add_route('hello', '/howdy/{name}') @@ -12,4 +10,4 @@ if __name__ == '__main__': config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/json/hello_world.jinja2 b/docs/quick_tour/json/hello_world.jinja2 index f6862e618..4fb9be074 100644 --- a/docs/quick_tour/json/hello_world.jinja2 +++ b/docs/quick_tour/json/hello_world.jinja2 @@ -1,8 +1,8 @@ - Quick Glance - + Hello World +

Hello {{ name }}!

diff --git a/docs/quick_tour/json/hello_world.pt b/docs/quick_tour/json/hello_world.pt deleted file mode 100644 index 711054aa9..000000000 --- a/docs/quick_tour/json/hello_world.pt +++ /dev/null @@ -1,17 +0,0 @@ - - - - Quick Glance - - - - - - - - -

Hello ${name}!

- - \ No newline at end of file diff --git a/docs/quick_tour/json/views.py b/docs/quick_tour/json/views.py index 583e220c7..22aa8aad6 100644 --- a/docs/quick_tour/json/views.py +++ b/docs/quick_tour/json/views.py @@ -1,13 +1,11 @@ from pyramid.view import view_config -@view_config(route_name='hello', renderer='hello_world.pt') +@view_config(route_name='hello', renderer='hello_world.jinja2') def hello_world(request): return dict(name=request.matchdict['name']) -# Start View 1 @view_config(route_name='hello_json', renderer='json') def hello_json(request): return [1, 2, 3] - # End View 1 \ No newline at end of file diff --git a/docs/quick_tour/requests/app.py b/docs/quick_tour/requests/app.py index 815714464..621b0693e 100644 --- a/docs/quick_tour/requests/app.py +++ b/docs/quick_tour/requests/app.py @@ -21,4 +21,4 @@ if __name__ == '__main__': config.add_view(hello_world, route_name='hello') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/routing/app.py b/docs/quick_tour/routing/app.py index 04a8a6344..12b547bfe 100644 --- a/docs/quick_tour/routing/app.py +++ b/docs/quick_tour/routing/app.py @@ -3,9 +3,7 @@ from pyramid.config import Configurator if __name__ == '__main__': config = Configurator() - # Start Route 1 config.add_route('hello', '/howdy/{first}/{last}') - # End Route 1 config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) diff --git a/docs/quick_tour/routing/views.py b/docs/quick_tour/routing/views.py index 8cb8d3780..8a3bd230e 100644 --- a/docs/quick_tour/routing/views.py +++ b/docs/quick_tour/routing/views.py @@ -2,9 +2,7 @@ from pyramid.response import Response from pyramid.view import view_config -# Start Route 1 @view_config(route_name='hello') def hello_world(request): body = '

Hi %(first)s %(last)s!

' % request.matchdict return Response(body) - # End Route 1 \ No newline at end of file diff --git a/docs/quick_tour/static_assets/app.py b/docs/quick_tour/static_assets/app.py index 9c808972f..1849c0a5a 100644 --- a/docs/quick_tour/static_assets/app.py +++ b/docs/quick_tour/static_assets/app.py @@ -4,11 +4,9 @@ from pyramid.config import Configurator if __name__ == '__main__': config = Configurator() config.add_route('hello', '/howdy/{name}') - # Start Static 1 config.add_static_view(name='static', path='static') - # End Static 1 config.include('pyramid_jinja2') config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/static_assets/hello_world.jinja2 b/docs/quick_tour/static_assets/hello_world.jinja2 index f6862e618..0fb2ce296 100644 --- a/docs/quick_tour/static_assets/hello_world.jinja2 +++ b/docs/quick_tour/static_assets/hello_world.jinja2 @@ -1,7 +1,7 @@ - Quick Glance + Hello World diff --git a/docs/quick_tour/static_assets/hello_world.pt b/docs/quick_tour/static_assets/hello_world.pt deleted file mode 100644 index 1797146eb..000000000 --- a/docs/quick_tour/static_assets/hello_world.pt +++ /dev/null @@ -1,16 +0,0 @@ - - - Quick Glance - - - - - - - - -

Hello ${name}!

- - \ No newline at end of file diff --git a/docs/quick_tour/static_assets/hello_world_static.jinja2 b/docs/quick_tour/static_assets/hello_world_static.jinja2 new file mode 100644 index 000000000..4fb9be074 --- /dev/null +++ b/docs/quick_tour/static_assets/hello_world_static.jinja2 @@ -0,0 +1,10 @@ + + + + Hello World + + + +

Hello {{ name }}!

+ + \ No newline at end of file diff --git a/docs/quick_tour/static_assets/views.py b/docs/quick_tour/static_assets/views.py index 90730ae32..7dbb45287 100644 --- a/docs/quick_tour/static_assets/views.py +++ b/docs/quick_tour/static_assets/views.py @@ -1,6 +1,6 @@ from pyramid.view import view_config -@view_config(route_name='hello', renderer='hello_world.pt') +@view_config(route_name='hello', renderer='hello_world.jinja2') def hello_world(request): return dict(name=request.matchdict['name']) diff --git a/docs/quick_tour/templating/app.py b/docs/quick_tour/templating/app.py index 6d1a29f4e..52b7faf55 100644 --- a/docs/quick_tour/templating/app.py +++ b/docs/quick_tour/templating/app.py @@ -4,7 +4,8 @@ from pyramid.config import Configurator if __name__ == '__main__': config = Configurator() config.add_route('hello', '/howdy/{name}') + config.include('pyramid_chameleon') config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/templating/views.py b/docs/quick_tour/templating/views.py index 6c7846efa..90730ae32 100644 --- a/docs/quick_tour/templating/views.py +++ b/docs/quick_tour/templating/views.py @@ -1,8 +1,6 @@ from pyramid.view import view_config -# Start View 1 @view_config(route_name='hello', renderer='hello_world.pt') def hello_world(request): return dict(name=request.matchdict['name']) - # End View 1 \ No newline at end of file diff --git a/docs/quick_tour/view_classes/app.py b/docs/quick_tour/view_classes/app.py index 468c8c29e..40faddd00 100644 --- a/docs/quick_tour/view_classes/app.py +++ b/docs/quick_tour/view_classes/app.py @@ -3,11 +3,11 @@ from pyramid.config import Configurator if __name__ == '__main__': config = Configurator() - # Start Routes 1 config.add_route('hello', '/howdy/{name}') - # End Routes 1 + config.add_route('hello_json', 'hello.json') + config.add_static_view(name='static', path='static') config.include('pyramid_jinja2') config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() diff --git a/docs/quick_tour/view_classes/hello.jinja2 b/docs/quick_tour/view_classes/hello.jinja2 index 3446b96ce..fc3058067 100644 --- a/docs/quick_tour/view_classes/hello.jinja2 +++ b/docs/quick_tour/view_classes/hello.jinja2 @@ -5,13 +5,11 @@

Hello {{ view.name }}!

-
- - - + + +
- \ No newline at end of file diff --git a/docs/quick_tour/view_classes/views.py b/docs/quick_tour/view_classes/views.py index 62556142e..10ff238c7 100644 --- a/docs/quick_tour/view_classes/views.py +++ b/docs/quick_tour/view_classes/views.py @@ -4,7 +4,6 @@ from pyramid.view import ( ) -# Start View 1 # One route, at /howdy/amy, so don't repeat on each @view_config @view_defaults(route_name='hello') class HelloWorldViews: @@ -29,4 +28,3 @@ class HelloWorldViews: def delete_view(self): print('Deleted') return dict() - # End View 1 \ No newline at end of file diff --git a/docs/quick_tour/views/app.py b/docs/quick_tour/views/app.py index 54dc9ed4b..e8df6eff2 100644 --- a/docs/quick_tour/views/app.py +++ b/docs/quick_tour/views/app.py @@ -10,4 +10,4 @@ if __name__ == '__main__': config.scan('views') app = config.make_wsgi_app() server = make_server('0.0.0.0', 6543, app) - server.serve_forever() \ No newline at end of file + server.serve_forever() -- cgit v1.2.3 From 5adb45a47e4ebfff5d2ea28833ef29a7f3ddbb25 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 22 Jan 2016 15:15:34 -0800 Subject: Add Python support policy (see https://github.com/Pylons/pyramid/pull/2256#issuecomment-174029882) --- docs/narr/upgrading.rst | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'docs') diff --git a/docs/narr/upgrading.rst b/docs/narr/upgrading.rst index db9b5e090..cacfba92a 100644 --- a/docs/narr/upgrading.rst +++ b/docs/narr/upgrading.rst @@ -75,6 +75,27 @@ changes are noted in the :ref:`changelog`, so it's possible to know that you should change older spellings to newer ones to ensure that people reading your code can find the APIs you're using in the Pyramid docs. + +Python support policy +~~~~~~~~~~~~~~~~~~~~~ + +At the time of a Pyramid version release, each supports all versions of Python +through the end of their lifespans. The end-of-life for a given version of +Python is when security updates are no longer released. + +- `Python 3.2 Lifespan `_ + ends February 2016. +- `Python 3.3 Lifespan `_ + ends September 2017. +- `Python 3.4 Lifespan `_ TBD. +- `Python 3.5 Lifespan `_ TBD. +- `Python 3.6 Lifespan `_ + December 2021. + +To determine the Python support for a specific release of Pyramid, view its +``tox.ini`` file at the root of the repository's version. + + Consulting the change history ----------------------------- -- cgit v1.2.3 From 6a936654276b83ccd379c739e3c39d5a25457ab3 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 23 Jan 2016 05:04:45 -0800 Subject: Complete overhaul of Quick Tour - Databases and Forms --- docs/quick_tour.rst | 92 ++++++------ docs/quick_tour/sqla_demo/README.txt | 6 +- docs/quick_tour/sqla_demo/development.ini | 2 +- docs/quick_tour/sqla_demo/production.ini | 2 +- docs/quick_tour/sqla_demo/setup.cfg | 27 ++++ docs/quick_tour/sqla_demo/setup.py | 11 +- docs/quick_tour/sqla_demo/sqla_demo.sqlite | Bin 3072 -> 0 bytes docs/quick_tour/sqla_demo/sqla_demo/__init__.py | 1 + docs/quick_tour/sqla_demo/sqla_demo/models.py | 10 +- .../sqla_demo/sqla_demo/scripts/initializedb.py | 9 +- .../sqla_demo/sqla_demo/static/pyramid-16x16.png | Bin 0 -> 1319 bytes .../sqla_demo/sqla_demo/static/pyramid.png | Bin 33055 -> 12901 bytes .../sqla_demo/sqla_demo/static/theme.css | 154 +++++++++++++++++++++ .../sqla_demo/sqla_demo/static/theme.min.css | 1 + .../sqla_demo/sqla_demo/templates/mytemplate.pt | 131 ++++++++---------- docs/quick_tour/sqla_demo/sqla_demo/tests.py | 26 +++- docs/quick_tour/sqla_demo/sqla_demo/views.py | 5 +- 17 files changed, 338 insertions(+), 139 deletions(-) create mode 100644 docs/quick_tour/sqla_demo/setup.cfg delete mode 100644 docs/quick_tour/sqla_demo/sqla_demo.sqlite create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/theme.css create mode 100644 docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css (limited to 'docs') diff --git a/docs/quick_tour.rst b/docs/quick_tour.rst index 220fd4bca..a7c184776 100644 --- a/docs/quick_tour.rst +++ b/docs/quick_tour.rst @@ -812,17 +812,16 @@ We need to update our Jinja2 template to show counter increment in the session: :ref:`flash_messages`, :ref:`session_module`, and :term:`pyramid_redis_sessions`. + Databases ========= -Web applications mean data. Data means databases. Frequently SQL -databases. SQL databases frequently mean an "ORM" -(object-relational mapper.) In Python, ORM usually leads to the -mega-quality *SQLAlchemy*, a Python package that greatly eases working -with databases. +Web applications mean data. Data means databases. Frequently SQL databases. SQL +databases frequently mean an "ORM" (object-relational mapper.) In Python, ORM +usually leads to the mega-quality *SQLAlchemy*, a Python package that greatly +eases working with databases. -Pyramid and SQLAlchemy are great friends. That friendship includes a -scaffold! +Pyramid and SQLAlchemy are great friends. That friendship includes a scaffold! .. code-block:: bash @@ -830,50 +829,53 @@ scaffold! $ cd sqla_demo $ python setup.py develop -We now have a working sample SQLAlchemy application with all -dependencies installed. The sample project provides a console script to -initialize a SQLite database with tables. Let's run it and then start -the application: +We now have a working sample SQLAlchemy application with all dependencies +installed. The sample project provides a console script to initialize a SQLite +database with tables. Let's run it, then start the application: .. code-block:: bash $ initialize_sqla_demo_db development.ini $ pserve development.ini -The ORM eases the mapping of database structures into a programming -language. SQLAlchemy uses "models" for this mapping. The scaffold -generated a sample model: +The ORM eases the mapping of database structures into a programming language. +SQLAlchemy uses "models" for this mapping. The scaffold generated a sample +model: .. literalinclude:: quick_tour/sqla_demo/sqla_demo/models.py - :start-after: Start Sphinx Include - :end-before: End Sphinx Include + :language: python + :linenos: + :lineno-start: 21 + :lines: 21- -View code, which mediates the logic between web requests and the rest -of the system, can then easily get at the data thanks to SQLAlchemy: +View code, which mediates the logic between web requests and the rest of the +system, can then easily get at the data thanks to SQLAlchemy: .. literalinclude:: quick_tour/sqla_demo/sqla_demo/views.py - :start-after: Start Sphinx Include - :end-before: End Sphinx Include + :language: python + :linenos: + :lineno-start: 12 + :lines: 12-18 + :emphasize-lines: 4 .. seealso:: See also: - :ref:`Quick Tutorial Databases `, - `SQLAlchemy `_, - :ref:`making_a_console_script`, - :ref:`bfg_sql_wiki_tutorial`, and - :ref:`Application Transactions With pyramid_tm ` + :ref:`Quick Tutorial Databases `, `SQLAlchemy + `_, :ref:`making_a_console_script`, + :ref:`bfg_sql_wiki_tutorial`, and :ref:`Application Transactions with + pyramid_tm `. + Forms ===== -Developers have lots of opinions about web forms, and thus there are many -form libraries for Python. Pyramid doesn't directly bundle a form -library, but *Deform* is a popular choice for forms, -along with its related *Colander* schema system. +Developers have lots of opinions about web forms, thus there are many form +libraries for Python. Pyramid doesn't directly bundle a form library, but +*Deform* is a popular choice for forms, along with its related *Colander* +schema system. -As an example, imagine we want a form that edits a wiki page. The form -should have two fields on it, one of them a required title and the -other a rich text editor for the body. With Deform we can express this -as a Colander schema: +As an example, imagine we want a form that edits a wiki page. The form should +have two fields on it, one of them a required title and the other a rich text +editor for the body. With Deform we can express this as a Colander schema: .. code-block:: python @@ -884,8 +886,8 @@ as a Colander schema: widget=deform.widget.RichTextWidget() ) -With this in place, we can render the HTML for a form, -perhaps with form data from an existing page: +With this in place, we can render the HTML for a form, perhaps with form data +from an existing page: .. code-block:: python @@ -909,20 +911,18 @@ We'd like to handle form submission, validation, and saving: page['title'] = appstruct['title'] page['body'] = appstruct['body'] -Deform and Colander provide a very flexible combination for forms, -widgets, schemas, and validation. Recent versions of Deform also -include a :ref:`retail mode ` for gaining Deform -features on custom forms. +Deform and Colander provide a very flexible combination for forms, widgets, +schemas, and validation. Recent versions of Deform also include a :ref:`retail +mode ` for gaining Deform features on custom forms. -Also the ``deform_bootstrap`` Pyramid add-on restyles the stock Deform -widgets using attractive CSS from Twitter Bootstrap and more powerful widgets -from Chosen. +Also the ``deform_bootstrap`` Pyramid add-on restyles the stock Deform widgets +using attractive CSS from Twitter Bootstrap and more powerful widgets from +Chosen. .. seealso:: See also: - :ref:`Quick Tutorial Forms `, - :ref:`Deform `, - :ref:`Colander `, and - `deform_bootstrap `_ + :ref:`Quick Tutorial Forms `, :ref:`Deform `, + :ref:`Colander `, and `deform_bootstrap + `_. Conclusion ========== diff --git a/docs/quick_tour/sqla_demo/README.txt b/docs/quick_tour/sqla_demo/README.txt index f35d3aec5..c7f9d6474 100644 --- a/docs/quick_tour/sqla_demo/README.txt +++ b/docs/quick_tour/sqla_demo/README.txt @@ -6,9 +6,9 @@ Getting Started - cd -- $venv/bin/python setup.py develop +- $VENV/bin/python setup.py develop -- $venv/bin/initialize_sqla_demo_db development.ini +- $VENV/bin/initialize_sqla_demo_db development.ini -- $venv/bin/pserve development.ini +- $VENV/bin/pserve development.ini diff --git a/docs/quick_tour/sqla_demo/development.ini b/docs/quick_tour/sqla_demo/development.ini index 174468abf..cdf20638e 100644 --- a/docs/quick_tour/sqla_demo/development.ini +++ b/docs/quick_tour/sqla_demo/development.ini @@ -68,4 +68,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/sqla_demo/production.ini b/docs/quick_tour/sqla_demo/production.ini index dc0ba304f..38f3b6318 100644 --- a/docs/quick_tour/sqla_demo/production.ini +++ b/docs/quick_tour/sqla_demo/production.ini @@ -59,4 +59,4 @@ level = NOTSET formatter = generic [formatter_generic] -format = %(asctime)s %(levelname)-5.5s [%(name)s][%(threadName)s] %(message)s +format = %(asctime)s %(levelname)-5.5s [%(name)s:%(lineno)s][%(threadName)s] %(message)s diff --git a/docs/quick_tour/sqla_demo/setup.cfg b/docs/quick_tour/sqla_demo/setup.cfg new file mode 100644 index 000000000..9f91cd122 --- /dev/null +++ b/docs/quick_tour/sqla_demo/setup.cfg @@ -0,0 +1,27 @@ +[nosetests] +match=^test +nocapture=1 +cover-package=sqla_demo +with-coverage=1 +cover-erase=1 + +[compile_catalog] +directory = sqla_demo/locale +domain = sqla_demo +statistics = true + +[extract_messages] +add_comments = TRANSLATORS: +output_file = sqla_demo/locale/sqla_demo.pot +width = 80 + +[init_catalog] +domain = sqla_demo +input_file = sqla_demo/locale/sqla_demo.pot +output_dir = sqla_demo/locale + +[update_catalog] +domain = sqla_demo +input_file = sqla_demo/locale/sqla_demo.pot +output_dir = sqla_demo/locale +previous = true diff --git a/docs/quick_tour/sqla_demo/setup.py b/docs/quick_tour/sqla_demo/setup.py index ac2eed035..a9a8842e2 100644 --- a/docs/quick_tour/sqla_demo/setup.py +++ b/docs/quick_tour/sqla_demo/setup.py @@ -3,15 +3,18 @@ import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) -README = open(os.path.join(here, 'README.txt')).read() -CHANGES = open(os.path.join(here, 'CHANGES.txt')).read() +with open(os.path.join(here, 'README.txt')) as f: + README = f.read() +with open(os.path.join(here, 'CHANGES.txt')) as f: + CHANGES = f.read() requires = [ 'pyramid', + 'pyramid_chameleon', + 'pyramid_debugtoolbar', + 'pyramid_tm', 'SQLAlchemy', 'transaction', - 'pyramid_tm', - 'pyramid_debugtoolbar', 'zope.sqlalchemy', 'waitress', ] diff --git a/docs/quick_tour/sqla_demo/sqla_demo.sqlite b/docs/quick_tour/sqla_demo/sqla_demo.sqlite deleted file mode 100644 index fa6adb104..000000000 Binary files a/docs/quick_tour/sqla_demo/sqla_demo.sqlite and /dev/null differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/__init__.py b/docs/quick_tour/sqla_demo/sqla_demo/__init__.py index aac7c5e69..867049e4f 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/__init__.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/__init__.py @@ -14,6 +14,7 @@ def main(global_config, **settings): DBSession.configure(bind=engine) Base.metadata.bind = engine config = Configurator(settings=settings) + config.include('pyramid_chameleon') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route('home', '/') config.scan() diff --git a/docs/quick_tour/sqla_demo/sqla_demo/models.py b/docs/quick_tour/sqla_demo/sqla_demo/models.py index 3dfb40e58..a0d3e7b71 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/models.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/models.py @@ -1,5 +1,6 @@ from sqlalchemy import ( Column, + Index, Integer, Text, ) @@ -16,14 +17,11 @@ from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() -# Start Sphinx Include + class MyModel(Base): __tablename__ = 'models' id = Column(Integer, primary_key=True) - name = Column(Text, unique=True) + name = Column(Text) value = Column(Integer) - def __init__(self, name, value): - self.name = name - self.value = value - # End Sphinx Include +Index('my_index', MyModel.name, unique=True, mysql_length=255) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py b/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py index 66feb3008..7dfdece15 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/scripts/initializedb.py @@ -9,6 +9,8 @@ from pyramid.paster import ( setup_logging, ) +from pyramid.scripts.common import parse_vars + from ..models import ( DBSession, MyModel, @@ -18,17 +20,18 @@ from ..models import ( def usage(argv): cmd = os.path.basename(argv[0]) - print('usage: %s \n' + print('usage: %s [var=value]\n' '(example: "%s development.ini")' % (cmd, cmd)) sys.exit(1) def main(argv=sys.argv): - if len(argv) != 2: + if len(argv) < 2: usage(argv) config_uri = argv[1] + options = parse_vars(argv[2:]) setup_logging(config_uri) - settings = get_appsettings(config_uri) + settings = get_appsettings(config_uri, options=options) engine = engine_from_config(settings, 'sqlalchemy.') DBSession.configure(bind=engine) Base.metadata.create_all(engine) diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png new file mode 100644 index 000000000..979203112 Binary files /dev/null and b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid-16x16.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png index 347e05549..4ab837be9 100644 Binary files a/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png and b/docs/quick_tour/sqla_demo/sqla_demo/static/pyramid.png differ diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css new file mode 100644 index 000000000..0f4b1a4d4 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.css @@ -0,0 +1,154 @@ +@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700); +body { + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-weight: 300; + color: #ffffff; + background: #bc2131; +} +h1, +h2, +h3, +h4, +h5, +h6 { + font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif; + font-weight: 300; +} +p { + font-weight: 300; +} +.font-normal { + font-weight: 400; +} +.font-semi-bold { + font-weight: 600; +} +.font-bold { + font-weight: 700; +} +.starter-template { + margin-top: 250px; +} +.starter-template .content { + margin-left: 10px; +} +.starter-template .content h1 { + margin-top: 10px; + font-size: 60px; +} +.starter-template .content h1 .smaller { + font-size: 40px; + color: #f2b7bd; +} +.starter-template .content .lead { + font-size: 25px; + color: #f2b7bd; +} +.starter-template .content .lead .font-normal { + color: #ffffff; +} +.starter-template .links { + float: right; + right: 0; + margin-top: 125px; +} +.starter-template .links ul { + display: block; + padding: 0; + margin: 0; +} +.starter-template .links ul li { + list-style: none; + display: inline; + margin: 0 10px; +} +.starter-template .links ul li:first-child { + margin-left: 0; +} +.starter-template .links ul li:last-child { + margin-right: 0; +} +.starter-template .links ul li.current-version { + color: #f2b7bd; + font-weight: 400; +} +.starter-template .links ul li a, a { + color: #f2b7bd; + text-decoration: underline; +} +.starter-template .links ul li a:hover, a:hover { + color: #ffffff; + text-decoration: underline; +} +.starter-template .links ul li .icon-muted { + color: #eb8b95; + margin-right: 5px; +} +.starter-template .links ul li:hover .icon-muted { + color: #ffffff; +} +.starter-template .copyright { + margin-top: 10px; + font-size: 0.9em; + color: #f2b7bd; + text-transform: lowercase; + float: right; + right: 0; +} +@media (max-width: 1199px) { + .starter-template .content h1 { + font-size: 45px; + } + .starter-template .content h1 .smaller { + font-size: 30px; + } + .starter-template .content .lead { + font-size: 20px; + } +} +@media (max-width: 991px) { + .starter-template { + margin-top: 0; + } + .starter-template .logo { + margin: 40px auto; + } + .starter-template .content { + margin-left: 0; + text-align: center; + } + .starter-template .content h1 { + margin-bottom: 20px; + } + .starter-template .links { + float: none; + text-align: center; + margin-top: 60px; + } + .starter-template .copyright { + float: none; + text-align: center; + } +} +@media (max-width: 767px) { + .starter-template .content h1 .smaller { + font-size: 25px; + display: block; + } + .starter-template .content .lead { + font-size: 16px; + } + .starter-template .links { + margin-top: 40px; + } + .starter-template .links ul li { + display: block; + margin: 0; + } + .starter-template .links ul li .icon-muted { + display: none; + } + .starter-template .copyright { + margin-top: 20px; + } +} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css new file mode 100644 index 000000000..0d25de5b6 --- /dev/null +++ b/docs/quick_tour/sqla_demo/sqla_demo/static/theme.min.css @@ -0,0 +1 @@ +@import url(//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700);body{font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:300;color:#fff;background:#bc2131}h1,h2,h3,h4,h5,h6{font-family:"Open Sans","Helvetica Neue",Helvetica,Arial,sans-serif;font-weight:300}p{font-weight:300}.font-normal{font-weight:400}.font-semi-bold{font-weight:600}.font-bold{font-weight:700}.starter-template{margin-top:250px}.starter-template .content{margin-left:10px}.starter-template .content h1{margin-top:10px;font-size:60px}.starter-template .content h1 .smaller{font-size:40px;color:#f2b7bd}.starter-template .content .lead{font-size:25px;color:#f2b7bd}.starter-template .content .lead .font-normal{color:#fff}.starter-template .links{float:right;right:0;margin-top:125px}.starter-template .links ul{display:block;padding:0;margin:0}.starter-template .links ul li{list-style:none;display:inline;margin:0 10px}.starter-template .links ul li:first-child{margin-left:0}.starter-template .links ul li:last-child{margin-right:0}.starter-template .links ul li.current-version{color:#f2b7bd;font-weight:400}.starter-template .links ul li a,a{color:#f2b7bd;text-decoration:underline}.starter-template .links ul li a:hover,a:hover{color:#fff;text-decoration:underline}.starter-template .links ul li .icon-muted{color:#eb8b95;margin-right:5px}.starter-template .links ul li:hover .icon-muted{color:#fff}.starter-template .copyright{margin-top:10px;font-size:.9em;color:#f2b7bd;text-transform:lowercase;float:right;right:0}@media (max-width:1199px){.starter-template .content h1{font-size:45px}.starter-template .content h1 .smaller{font-size:30px}.starter-template .content .lead{font-size:20px}}@media (max-width:991px){.starter-template{margin-top:0}.starter-template .logo{margin:40px auto}.starter-template .content{margin-left:0;text-align:center}.starter-template .content h1{margin-bottom:20px}.starter-template .links{float:none;text-align:center;margin-top:60px}.starter-template .copyright{float:none;text-align:center}}@media (max-width:767px){.starter-template .content h1 .smaller{font-size:25px;display:block}.starter-template .content .lead{font-size:16px}.starter-template .links{margin-top:40px}.starter-template .links ul li{display:block;margin:0}.starter-template .links ul li .icon-muted{display:none}.starter-template .copyright{margin-top:20px}} diff --git a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt index 321c0f5fb..99df4a8b7 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt +++ b/docs/quick_tour/sqla_demo/sqla_demo/templates/mytemplate.pt @@ -1,76 +1,67 @@ - - - - The Pyramid Web Framework - - - - - - - - - - -
-
-
-
pyramid
-
-
-
-
-

- Welcome to ${project}, an application generated by
- the Pyramid web framework. -

-
-
-
-
-
-

Search documentation

-
- - -
+ + + + + + + + + + + Alchemy Scaffold for The Pyramid Web Framework + + + + + + + + + + + + + +
+
+
+
+ +
+
+
+

Pyramid Alchemy scaffold

+

Welcome to ${project}, an application generated by
the Pyramid Web Framework 1.6.

+
+
-
-
- - + + + + + + + diff --git a/docs/quick_tour/sqla_demo/sqla_demo/tests.py b/docs/quick_tour/sqla_demo/sqla_demo/tests.py index 6fef6d695..be288d580 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/tests.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/tests.py @@ -6,7 +6,7 @@ from pyramid import testing from .models import DBSession -class TestMyView(unittest.TestCase): +class TestMyViewSuccessCondition(unittest.TestCase): def setUp(self): self.config = testing.setUp() from sqlalchemy import create_engine @@ -25,9 +25,31 @@ class TestMyView(unittest.TestCase): DBSession.remove() testing.tearDown() - def test_it(self): + def test_passing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'sqla_demo') + + +class TestMyViewFailureCondition(unittest.TestCase): + def setUp(self): + self.config = testing.setUp() + from sqlalchemy import create_engine + engine = create_engine('sqlite://') + from .models import ( + Base, + MyModel, + ) + DBSession.configure(bind=engine) + + def tearDown(self): + DBSession.remove() + testing.tearDown() + + def test_failing_view(self): + from .views import my_view + request = testing.DummyRequest() + info = my_view(request) + self.assertEqual(info.status_int, 500) \ No newline at end of file diff --git a/docs/quick_tour/sqla_demo/sqla_demo/views.py b/docs/quick_tour/sqla_demo/sqla_demo/views.py index 768a7e42e..964f76441 100644 --- a/docs/quick_tour/sqla_demo/sqla_demo/views.py +++ b/docs/quick_tour/sqla_demo/sqla_demo/views.py @@ -12,19 +12,18 @@ from .models import ( @view_config(route_name='home', renderer='templates/mytemplate.pt') def my_view(request): try: - # Start Sphinx Include one = DBSession.query(MyModel).filter(MyModel.name == 'one').first() - # End Sphinx Include except DBAPIError: return Response(conn_err_msg, content_type='text/plain', status_int=500) return {'one': one, 'project': 'sqla_demo'} + conn_err_msg = """\ Pyramid is having a problem using your SQL database. The problem might be caused by one of the following things: 1. You may need to run the "initialize_sqla_demo_db" script - to initialize your database tables. Check your virtual + to initialize your database tables. Check your virtual environment's "bin" directory for this script and try to run it. 2. Your database server may not be running. Check that the -- cgit v1.2.3 From 1779c2a7c7653142cc3164e83b1f0fe43850f97b Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 24 Jan 2016 00:15:46 -0800 Subject: Bump sphinx to 1.3.5; revert comment syntax. Closes #2251. --- docs/quick_tour/requests/app.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/quick_tour/requests/app.py b/docs/quick_tour/requests/app.py index 621b0693e..f55264cff 100644 --- a/docs/quick_tour/requests/app.py +++ b/docs/quick_tour/requests/app.py @@ -4,7 +4,7 @@ from pyramid.response import Response def hello_world(request): - """ Some parameters from a request such as /?name=lisa """ + # Some parameters from a request such as /?name=lisa url = request.url name = request.params.get('name', 'No Name Provided') -- cgit v1.2.3 From 3cdd3cedb9a120228f5bb2c0a9d53c0017b55cd9 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 24 Jan 2016 01:02:42 -0800 Subject: Use proper syntax in code samples to allow highlighting and avoid errors. See https://github.com/sphinx-doc/sphinx/issues/2264 --- docs/narr/project.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/narr/project.rst b/docs/narr/project.rst index 5103bb6b8..923fde436 100644 --- a/docs/narr/project.rst +++ b/docs/narr/project.rst @@ -447,7 +447,7 @@ commenting out a line. For example, instead of: :linenos: [app:main] - ... + # ... elided configuration pyramid.includes = pyramid_debugtoolbar @@ -457,7 +457,7 @@ Put a hash mark at the beginning of the ``pyramid_debugtoolbar`` line: :linenos: [app:main] - ... + # ... elided configuration pyramid.includes = # pyramid_debugtoolbar -- cgit v1.2.3 From 22f221099e785cb763e9659da029933ca9fc11e6 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 24 Jan 2016 01:10:13 -0800 Subject: Use proper syntax names in code samples to allow highlighting and avoid errors. See https://github.com/sphinx-doc/sphinx/issues/2264 --- docs/narr/webob.rst | 2 +- docs/quick_tutorial/requirements.rst | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'docs') diff --git a/docs/narr/webob.rst b/docs/narr/webob.rst index f18cf1dfb..cfcf532bc 100644 --- a/docs/narr/webob.rst +++ b/docs/narr/webob.rst @@ -269,7 +269,7 @@ to a :app:`Pyramid` application: When such a request reaches a view in your application, the ``request.json_body`` attribute will be available in the view callable body. -.. code-block:: javascript +.. code-block:: python @view_config(renderer='string') def aview(request): diff --git a/docs/quick_tutorial/requirements.rst b/docs/quick_tutorial/requirements.rst index 6d5a965cd..f855dcb55 100644 --- a/docs/quick_tutorial/requirements.rst +++ b/docs/quick_tutorial/requirements.rst @@ -109,7 +109,7 @@ For Linux, the commands to do so are as follows: For Windows: -.. code-block:: posh +.. code-block:: ps1con # Windows c:\> cd \ -- cgit v1.2.3 From 65bb52bafa5d44b378f01dfb47816a952bf93a66 Mon Sep 17 00:00:00 2001 From: Svintsov Dmitry Date: Sun, 24 Jan 2016 16:36:43 +0500 Subject: fix indent in docs --- docs/narr/install.rst | 4 ++-- docs/narr/subrequest.rst | 14 +++++++------- 2 files changed, 9 insertions(+), 9 deletions(-) (limited to 'docs') diff --git a/docs/narr/install.rst b/docs/narr/install.rst index c4e3e2c5f..767b16fc0 100644 --- a/docs/narr/install.rst +++ b/docs/narr/install.rst @@ -292,7 +292,7 @@ After you've got your virtualenv installed, you may install :app:`Pyramid` itself using the following commands: .. parsed-literal:: - + $ $VENV/bin/easy_install "pyramid==\ |release|\ " The ``easy_install`` command will take longer than the previous ones to @@ -371,7 +371,7 @@ You can use Pyramid on Windows under Python 2 or 3. installed: .. parsed-literal:: - + c:\\env> %VENV%\\Scripts\\easy_install "pyramid==\ |release|\ " What Gets Installed diff --git a/docs/narr/subrequest.rst b/docs/narr/subrequest.rst index 02ae14aa5..daa3cc43f 100644 --- a/docs/narr/subrequest.rst +++ b/docs/narr/subrequest.rst @@ -17,7 +17,7 @@ application. Here's an example application which uses a subrequest: .. code-block:: python - :linenos: + :linenos: from wsgiref.simple_server import make_server from pyramid.config import Configurator @@ -61,8 +61,8 @@ adapter when found and invoked via object: .. code-block:: python - :linenos: - :emphasize-lines: 11 + :linenos: + :emphasize-lines: 11 from wsgiref.simple_server import make_server from pyramid.config import Configurator @@ -106,8 +106,8 @@ exception, the exception will be raised to the caller of :term:`exception view` configured: .. code-block:: python - :linenos: - :emphasize-lines: 11-16 + :linenos: + :emphasize-lines: 11-16 from wsgiref.simple_server import make_server from pyramid.config import Configurator @@ -175,8 +175,8 @@ We can cause the subrequest to be run through the tween stack by passing :meth:`~pyramid.request.Request.invoke_subrequest`, like this: .. code-block:: python - :linenos: - :emphasize-lines: 7 + :linenos: + :emphasize-lines: 7 from wsgiref.simple_server import make_server from pyramid.config import Configurator -- cgit v1.2.3 From 41aa6080791c082c2eeffa2540d53bddea09decd Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 25 Jan 2016 00:50:01 -0800 Subject: minor grammar and rst fixes, rewrap to 79 columns --- docs/designdefense.rst | 101 +++++++++++++++++++++++++------------------------ 1 file changed, 51 insertions(+), 50 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index c58cc5403..f4decebe6 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -630,7 +630,8 @@ dependencies by forcing us to make better packaging decisions. Removing Chameleon and Mako templating system dependencies in the Pyramid core in 1.5 let us shed most of the remainder of them. -Pyramid "Cheats" To Obtain Speed + +Pyramid "Cheats" to Obtain Speed -------------------------------- Complaints have been lodged by other web framework authors at various times @@ -639,10 +640,11 @@ mechanism is our use (transitively) of the C extensions provided by :mod:`zope.interface` to do fast lookups. Another claimed cheating mechanism is the religious avoidance of extraneous function calls. -If there's such a thing as cheating to get better performance, we want to -cheat as much as possible. We optimize :app:`Pyramid` aggressively. This -comes at a cost: the core code has sections that could be expressed more -readably. As an amelioration, we've commented these sections liberally. +If there's such a thing as cheating to get better performance, we want to cheat +as much as possible. We optimize :app:`Pyramid` aggressively. This comes at a +cost. The core code has sections that could be expressed with more readability. +As an amelioration, we've commented these sections liberally. + Pyramid Gets Its Terminology Wrong ("MVC") ------------------------------------------ @@ -655,8 +657,8 @@ existing "MVC" framework uses its terminology. For example, you probably expect that models are ORM models, controllers are classes that have methods that map to URLs, and views are templates. :app:`Pyramid` indeed has each of these concepts, and each probably *works* almost exactly like your existing -"MVC" web framework. We just don't use the MVC terminology, as we can't -square its usage in the web framework space with historical reality. +"MVC" web framework. We just don't use the MVC terminology, as we can't square +its usage in the web framework space with historical reality. People very much want to give web applications the same properties as common desktop GUI platforms by using similar terminology, and to provide some frame @@ -665,60 +667,59 @@ hang together. But in the opinion of the author, "MVC" doesn't match the web very well in general. Quoting from the `Model-View-Controller Wikipedia entry `_: -.. code-block:: text + Though MVC comes in different flavors, control flow is generally as + follows: - Though MVC comes in different flavors, control flow is generally as - follows: + The user interacts with the user interface in some way (for example, + presses a mouse button). - The user interacts with the user interface in some way (for - example, presses a mouse button). + The controller handles the input event from the user interface, often via + a registered handler or callback and converts the event into appropriate + user action, understandable for the model. - The controller handles the input event from the user interface, - often via a registered handler or callback and converts the event - into appropriate user action, understandable for the model. + The controller notifies the model of the user action, possibly resulting + in a change in the model's state. (For example, the controller updates the + user's shopping cart.)[5] - The controller notifies the model of the user action, possibly - resulting in a change in the model's state. (For example, the - controller updates the user's shopping cart.)[5] + A view queries the model in order to generate an appropriate user + interface (for example, the view lists the shopping cart's contents). Note + that the view gets its own data from the model. - A view queries the model in order to generate an appropriate - user interface (for example, the view lists the shopping cart's - contents). Note that the view gets its own data from the model. + The controller may (in some implementations) issue a general instruction + to the view to render itself. In others, the view is automatically + notified by the model of changes in state (Observer) which require a + screen update. - The controller may (in some implementations) issue a general - instruction to the view to render itself. In others, the view is - automatically notified by the model of changes in state - (Observer) which require a screen update. - - The user interface waits for further user interactions, which - restarts the cycle. + The user interface waits for further user interactions, which restarts the + cycle. To the author, it seems as if someone edited this Wikipedia definition, tortuously couching concepts in the most generic terms possible in order to -account for the use of the term "MVC" by current web frameworks. I doubt -such a broad definition would ever be agreed to by the original authors of -the MVC pattern. But *even so*, it seems most MVC web frameworks fail to -meet even this falsely generic definition. +account for the use of the term "MVC" by current web frameworks. I doubt such +a broad definition would ever be agreed to by the original authors of the MVC +pattern. But *even so*, it seems most MVC web frameworks fail to meet even +this falsely generic definition. For example, do your templates (views) always query models directly as is -claimed in "note that the view gets its own data from the model"? Probably -not. My "controllers" tend to do this, massaging the data for easier use by -the "view" (template). What do you do when your "controller" returns JSON? Do -your controllers use a template to generate JSON? If not, what's the "view" -then? Most MVC-style GUI web frameworks have some sort of event system -hooked up that lets the view detect when the model changes. The web just has -no such facility in its current form: it's effectively pull-only. - -So, in the interest of not mistaking desire with reality, and instead of -trying to jam the square peg that is the web into the round hole of "MVC", we -just punt and say there are two things: resources and views. The resource -tree represents a site structure, the view presents a resource. The -templates are really just an implementation detail of any given view: a view -doesn't need a template to return a response. There's no "controller": it -just doesn't exist. The "model" is either represented by the resource tree -or by a "domain model" (like a SQLAlchemy model) that is separate from the -framework entirely. This seems to us like more reasonable terminology, given -the current constraints of the web. +claimed in "note that the view gets its own data from the model"? Probably not. +My "controllers" tend to do this, massaging the data for easier use by the +"view" (template). What do you do when your "controller" returns JSON? Do your +controllers use a template to generate JSON? If not, what's the "view" then? +Most MVC-style GUI web frameworks have some sort of event system hooked up that +lets the view detect when the model changes. The web just has no such facility +in its current form; it's effectively pull-only. + +So, in the interest of not mistaking desire with reality, and instead of trying +to jam the square peg that is the web into the round hole of "MVC", we just +punt and say there are two things: resources and views. The resource tree +represents a site structure, the view presents a resource. The templates are +really just an implementation detail of any given view. A view doesn't need a +template to return a response. There's no "controller"; it just doesn't exist. +The "model" is either represented by the resource tree or by a "domain model" +(like an SQLAlchemy model) that is separate from the framework entirely. This +seems to us like more reasonable terminology, given the current constraints of +the web. + .. _apps_are_extensible: -- cgit v1.2.3 From 628dac551663d6e676f6a3b35cb81375709c4525 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Tue, 26 Jan 2016 00:03:41 -0800 Subject: minor grammar and rst fixes, rewrap to 79 columns, in section "Pyramid Applications Are Extensible" --- docs/designdefense.rst | 183 ++++++++++++++++++++++++------------------------- 1 file changed, 90 insertions(+), 93 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index f4decebe6..f757a8e70 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -723,125 +723,122 @@ the web. .. _apps_are_extensible: -Pyramid Applications are Extensible; I Don't Believe In Application Extensibility +Pyramid Applications Are Extensible; I Don't Believe in Application Extensibility --------------------------------------------------------------------------------- Any :app:`Pyramid` application written obeying certain constraints is *extensible*. This feature is discussed in the :app:`Pyramid` documentation -chapters named :ref:`extending_chapter` and :ref:`advconfig_narr`. It is -made possible by the use of the :term:`Zope Component Architecture` and -within :app:`Pyramid`. +chapters named :ref:`extending_chapter` and :ref:`advconfig_narr`. It is made +possible by the use of the :term:`Zope Component Architecture` within +:app:`Pyramid`. -"Extensible", in this context, means: +"Extensible" in this context means: -- The behavior of an application can be overridden or extended in a - particular *deployment* of the application without requiring that - the deployer modify the source of the original application. +- The behavior of an application can be overridden or extended in a particular + *deployment* of the application without requiring that the deployer modify + the source of the original application. -- The original developer is not required to anticipate any - extensibility plugpoints at application creation time to allow - fundamental application behavior to be overriden or extended. +- The original developer is not required to anticipate any extensibility + plug points at application creation time to allow fundamental application + behavior to be overridden or extended. - The original developer may optionally choose to anticipate an - application-specific set of plugpoints, which may be hooked by - a deployer. If he chooses to use the facilities provided by the - ZCA, the original developer does not need to think terribly hard - about the mechanics of introducing such a plugpoint. + application-specific set of plug points, which may be hooked by a deployer. + If they choose to use the facilities provided by the ZCA, the original + developer does not need to think terribly hard about the mechanics of + introducing such a plug point. Many developers seem to believe that creating extensible applications is not -worth it. They instead suggest that modifying the source of a given -application for each deployment to override behavior is more reasonable. -Much discussion about version control branching and merging typically ensues. - -It's clear that making every application extensible isn't required. The -majority of web applications only have a single deployment, and thus needn't -be extensible at all. However, some web applications have multiple -deployments, and some have *many* deployments. For example, a generic -content management system (CMS) may have basic functionality that needs to be -extended for a particular deployment. That CMS system may be deployed for -many organizations at many places. Some number of deployments of this CMS -may be deployed centrally by a third party and managed as a group. It's -easier to be able to extend such a system for each deployment via preordained -plugpoints than it is to continually keep each software branch of the system -in sync with some upstream source: the upstream developers may change code in -such a way that your changes to the same codebase conflict with theirs in -fiddly, trivial ways. Merging such changes repeatedly over the lifetime of a -deployment can be difficult and time consuming, and it's often useful to be -able to modify an application for a particular deployment in a less invasive -way. +worth it. They instead suggest that modifying the source of a given application +for each deployment to override behavior is more reasonable. Much discussion +about version control branching and merging typically ensues. + +It's clear that making every application extensible isn't required. The +majority of web applications only have a single deployment, and thus needn't be +extensible at all. However some web applications have multiple deployments, and +others have *many* deployments. For example, a generic content management +system (CMS) may have basic functionality that needs to be extended for a +particular deployment. That CMS may be deployed for many organizations at many +places. Some number of deployments of this CMS may be deployed centrally by a +third party and managed as a group. It's easier to be able to extend such a +system for each deployment via preordained plug points than it is to +continually keep each software branch of the system in sync with some upstream +source. The upstream developers may change code in such a way that your changes +to the same codebase conflict with theirs in fiddly, trivial ways. Merging such +changes repeatedly over the lifetime of a deployment can be difficult and time +consuming, and it's often useful to be able to modify an application for a +particular deployment in a less invasive way. If you don't want to think about :app:`Pyramid` application extensibility at -all, you needn't. You can ignore extensibility entirely. However, if you -follow the set of rules defined in :ref:`extending_chapter`, you don't need -to *make* your application extensible: any application you write in the -framework just *is* automatically extensible at a basic level. The -mechanisms that deployers use to extend it will be necessarily coarse: -typically, views, routes, and resources will be capable of being -overridden. But for most minor (and even some major) customizations, these -are often the only override plugpoints necessary: if the application doesn't -do exactly what the deployment requires, it's often possible for a deployer -to override a view, route, or resource and quickly make it do what he or she -wants it to do in ways *not necessarily anticipated by the original -developer*. Here are some example scenarios demonstrating the benefits of -such a feature. - -- If a deployment needs a different styling, the deployer may override the - main template and the CSS in a separate Python package which defines - overrides. - -- If a deployment needs an application page to do something differently, or - to expose more or different information, the deployer may override the - view that renders the page within a separate Python package. +all, you needn't. You can ignore extensibility entirely. However if you follow +the set of rules defined in :ref:`extending_chapter`, you don't need to *make* +your application extensible. Any application you write in the framework just +*is* automatically extensible at a basic level. The mechanisms that deployers +use to extend it will be necessarily coarse. Typically views, routes, and +resources will be capable of being overridden. But for most minor (and even +some major) customizations, these are often the only override plug points +necessary. If the application doesn't do exactly what the deployment requires, +it's often possible for a deployer to override a view, route, or resource, and +quickly make it do what they want it to do in ways *not necessarily anticipated +by the original developer*. Here are some example scenarios demonstrating the +benefits of such a feature. + +- If a deployment needs a different styling, the deployer may override the main + template and the CSS in a separate Python package which defines overrides. + +- If a deployment needs an application page to do something differently, or to + expose more or different information, the deployer may override the view that + renders the page within a separate Python package. - If a deployment needs an additional feature, the deployer may add a view to the override package. -As long as the fundamental design of the upstream package doesn't change, -these types of modifications often survive across many releases of the -upstream package without needing to be revisited. +As long as the fundamental design of the upstream package doesn't change, these +types of modifications often survive across many releases of the upstream +package without needing to be revisited. Extending an application externally is not a panacea, and carries a set of -risks similar to branching and merging: sometimes major changes upstream will -cause you to need to revisit and update some of your modifications. But you -won't regularly need to deal wth meaningless textual merge conflicts that -trivial changes to upstream packages often entail when it comes time to -update the upstream package, because if you extend an application externally, -there just is no textual merge done. Your modifications will also, for -whatever it's worth, be contained in one, canonical, well-defined place. +risks similar to branching and merging. Sometimes major changes upstream will +cause you to revisit and update some of your modifications. But you won't +regularly need to deal with meaningless textual merge conflicts that trivial +changes to upstream packages often entail when it comes time to update the +upstream package, because if you extend an application externally, there just +is no textual merge done. Your modifications will also, for whatever it's +worth, be contained in one, canonical, well-defined place. Branching an application and continually merging in order to get new features -and bugfixes is clearly useful. You can do that with a :app:`Pyramid` -application just as usefully as you can do it with any application. But +and bug fixes is clearly useful. You can do that with a :app:`Pyramid` +application just as usefully as you can do it with any application. But deployment of an application written in :app:`Pyramid` makes it possible to -avoid the need for this even if the application doesn't define any plugpoints -ahead of time. It's possible that promoters of competing web frameworks -dismiss this feature in favor of branching and merging because applications -written in their framework of choice aren't extensible out of the box in a -comparably fundamental way. +avoid the need for this even if the application doesn't define any plug points +ahead of time. It's possible that promoters of competing web frameworks dismiss +this feature in favor of branching and merging because applications written in +their framework of choice aren't extensible out of the box in a comparably +fundamental way. While :app:`Pyramid` applications are fundamentally extensible even if you don't write them with specific extensibility in mind, if you're moderately -adventurous, you can also take it a step further. If you learn more about -the :term:`Zope Component Architecture`, you can optionally use it to expose -other more domain-specific configuration plugpoints while developing an -application. The plugpoints you expose needn't be as coarse as the ones -provided automatically by :app:`Pyramid` itself. For example, you might -compose your own directive that configures a set of views for a prebaked -purpose (e.g. ``restview`` or somesuch) , allowing other people to refer to -that directive when they make declarations in the ``includeme`` of their -customization package. There is a cost for this: the developer of an -application that defines custom plugpoints for its deployers will need to -understand the ZCA or he will need to develop his own similar extensibility -system. - -Ultimately, any argument about whether the extensibility features lent to -applications by :app:`Pyramid` are good or bad is mostly pointless. You -needn't take advantage of the extensibility features provided by a particular +adventurous, you can also take it a step further. If you learn more about the +:term:`Zope Component Architecture`, you can optionally use it to expose other +more domain-specific configuration plug points while developing an application. +The plug points you expose needn't be as coarse as the ones provided +automatically by :app:`Pyramid` itself. For example, you might compose your own +directive that configures a set of views for a pre-baked purpose (e.g., +``restview`` or somesuch), allowing other people to refer to that directive +when they make declarations in the ``includeme`` of their customization +package. There is a cost for this: the developer of an application that defines +custom plug points for its deployers will need to understand the ZCA or they +will need to develop their own similar extensibility system. + +Ultimately any argument about whether the extensibility features lent to +applications by :app:`Pyramid` are good or bad is mostly pointless. You needn't +take advantage of the extensibility features provided by a particular :app:`Pyramid` application in order to affect a modification for a particular -set of its deployments. You can ignore the application's extensibility -plugpoints entirely, and use version control branching and merging to -manage application deployment modifications instead, as if you were deploying -an application written using any other web framework. +set of its deployments. You can ignore the application's extensibility plug +points entirely, and use version control branching and merging to manage +application deployment modifications instead, as if you were deploying an +application written using any other web framework. + Zope 3 Enforces "TTW" Authorization Checks By Default; Pyramid Does Not ----------------------------------------------------------------------- -- cgit v1.2.3 From 4df9a09807a844192e7769489d452a071b59c80c Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Wed, 27 Jan 2016 10:54:43 -0800 Subject: minor grammar fixes, rewrap to 79 columns, in section "Zope 3 Enforces 'TTW'..." --- docs/designdefense.rst | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index f757a8e70..b7aca07ea 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -840,17 +840,16 @@ application deployment modifications instead, as if you were deploying an application written using any other web framework. -Zope 3 Enforces "TTW" Authorization Checks By Default; Pyramid Does Not +Zope 3 Enforces "TTW" Authorization Checks by Default; Pyramid Does Not ----------------------------------------------------------------------- Challenge +++++++++ :app:`Pyramid` performs automatic authorization checks only at :term:`view` -execution time. Zope 3 wraps context objects with a `security proxy -`_, which causes Zope 3 to -do also security checks during attribute access. I like this, because it -means: +execution time. Zope 3 wraps context objects with a `security proxy +`_, which causes Zope 3 also +to do security checks during attribute access. I like this, because it means: #) When I use the security proxy machinery, I can have a view that conditionally displays certain HTML elements (like form fields) or @@ -882,7 +881,7 @@ web framework. And since we tend to use the same toolkit for all web applications, it's just never been a concern to be able to use the same set of restricted-execution -code under two web different frameworks. +code under two different web frameworks. Justifications for disabling security proxies by default notwithstanding, given that Zope 3 security proxies are viral by nature, the only requirement @@ -895,6 +894,7 @@ Zope3-security-proxy-wrapped objects for each traversed object (including the :term:`context` and the :term:`root`). This would have the effect of creating a more Zope3-like environment without much effort. + .. _http_exception_hierarchy: Pyramid uses its own HTTP exception class hierarchy rather than :mod:`webob.exc` -- cgit v1.2.3 From e636eeb1ad08dc0f5f1457ee086636045c4ce1e8 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 29 Jan 2016 00:32:31 -0800 Subject: minor grammar fixes, rewrap to 79 columns, in section "Pyramid uses its own HTTP exception class hierarchy" --- docs/designdefense.rst | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index b7aca07ea..2da10108a 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -907,28 +907,29 @@ much like the ones defined in :mod:`webob.exc`, (e.g., :class:`~pyramid.httpexceptions.HTTPNotFound` or :class:`~pyramid.httpexceptions.HTTPForbidden`). They have the same names and largely the same behavior, and all have a very similar implementation, but not -the same identity. Here's why they have a separate identity: +the same identity. Here's why they have a separate identity. - Making them separate allows the HTTP exception classes to subclass :class:`pyramid.response.Response`. This speeds up response generation - slightly due to the way the Pyramid router works. The same speedup could be + slightly due to the way the Pyramid router works. The same speed up could be gained by monkeypatching :class:`webob.response.Response`, but it's usually the case that monkeypatching turns out to be evil and wrong. -- Making them separate allows them to provide alternate ``__call__`` logic +- Making them separate allows them to provide alternate ``__call__`` logic, which also speeds up response generation. - Making them separate allows the exception classes to provide for the proper value of ``RequestClass`` (:class:`pyramid.request.Request`). -- Making them separate allows us freedom from having to think about backwards - compatibility code present in :mod:`webob.exc` having to do with Python 2.4, - which we no longer support in Pyramid 1.1+. +- Making them separate gives us freedom from thinking about backwards + compatibility code present in :mod:`webob.exc` related to Python 2.4, which + we no longer support in Pyramid 1.1+. - We change the behavior of two classes (:class:`~pyramid.httpexceptions.HTTPNotFound` and :class:`~pyramid.httpexceptions.HTTPForbidden`) in the module so that they - can be used by Pyramid internally for notfound and forbidden exceptions. + can be used by Pyramid internally for ``notfound`` and ``forbidden`` + exceptions. - Making them separate allows us to influence the docstrings of the exception classes to provide Pyramid-specific documentation. @@ -937,6 +938,7 @@ the same identity. Here's why they have a separate identity: Python 2.6 when the response objects are used as exceptions (related to ``self.message``). + .. _simpler_traversal_model: Pyramid has Simpler Traversal Machinery than Does Zope -- cgit v1.2.3 From bd88dcd361a7a25450ee4abb7416b83cddd93ee2 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 29 Jan 2016 22:43:22 -0800 Subject: update instructions for major release in conf.py html_theme_options --- docs/conf.py | 3 +++ 1 file changed, 3 insertions(+) (limited to 'docs') diff --git a/docs/conf.py b/docs/conf.py index 073811eca..4cac1e913 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -129,7 +129,10 @@ html_theme = 'pyramid' html_theme_path = pylons_sphinx_themes.get_html_themes_path() html_theme_options = dict( github_url='https://github.com/Pylons/pyramid', + # on master branch true, else false in_progress='true', + # on previous branches/major releases true, else false + outdated='false', ) # The name for this set of Sphinx documents. If None, it defaults to -- cgit v1.2.3 From 8d2a2b967ff912aa0b8e74128cf2b5473d6db44a Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Fri, 29 Jan 2016 23:20:25 -0800 Subject: fix heading under/overlines for rst syntax (cherry picked from commit 60b74ee) --- docs/tutorials/wiki/design.rst | 4 ++-- docs/tutorials/wiki2/design.rst | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'docs') diff --git a/docs/tutorials/wiki/design.rst b/docs/tutorials/wiki/design.rst index 49c30d29a..46c2a2f30 100644 --- a/docs/tutorials/wiki/design.rst +++ b/docs/tutorials/wiki/design.rst @@ -1,6 +1,6 @@ -========== +====== Design -========== +====== Following is a quick overview of the design of our wiki application, to help us understand the changes that we will be making as we work through the diff --git a/docs/tutorials/wiki2/design.rst b/docs/tutorials/wiki2/design.rst index e9f361e7d..52f2ce7a5 100644 --- a/docs/tutorials/wiki2/design.rst +++ b/docs/tutorials/wiki2/design.rst @@ -1,6 +1,6 @@ -========== +====== Design -========== +====== Following is a quick overview of the design of our wiki application, to help us understand the changes that we will be making as we work through the -- cgit v1.2.3 From 1cb1104f983ca92695ca24cb79ad6bfbb432aad3 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 30 Jan 2016 00:31:01 -0800 Subject: clean up principal and userid glossary entries for grammar, rst syntax --- docs/glossary.rst | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'docs') diff --git a/docs/glossary.rst b/docs/glossary.rst index 60f03f000..2683ff369 100644 --- a/docs/glossary.rst +++ b/docs/glossary.rst @@ -234,7 +234,7 @@ Glossary object *location-aware*. permission - A string or unicode object that represents an action being taken against + A string or Unicode object that represents an action being taken against a :term:`context` resource. A permission is associated with a view name and a resource type by the developer. Resources are decorated with security declarations (e.g. an :term:`ACL`), which reference these @@ -291,22 +291,22 @@ Glossary :term:`authorization policy`. principal - A *principal* is a string or unicode object representing an - entity, typically a user or group. Principals are provided by an - :term:`authentication policy`. For example, if a user had the - :term:`userid` `"bob"`, and was part of two groups named `"group foo"` - and "group bar", the request might have information attached to - it that would indicate that Bob was represented by three - principals: `"bob"`, `"group foo"` and `"group bar"`. + A *principal* is a string or Unicode object representing an entity, + typically a user or group. Principals are provided by an + :term:`authentication policy`. For example, if a user has the + :term:`userid` `bob`, and is a member of two groups named `group foo` and + `group bar`, then the request might have information attached to it + indicating that Bob was represented by three principals: `bob`, `group + foo` and `group bar`. userid - A *userid* is a string or unicode object used to identify and - authenticate a real-world user (or client). A userid is - supplied to an :term:`authentication policy` in order to discover - the user's :term:`principals `. The default behavior - of the authentication policies :app:`Pyramid` provides is to - return the user's userid as a principal, but this is not strictly - necessary in custom policies that define their principals differently. + A *userid* is a string or Unicode object used to identify and authenticate + a real-world user or client. A userid is supplied to an + :term:`authentication policy` in order to discover the user's + :term:`principals `. In the authentication policies which + :app:`Pyramid` provides, the default behavior returns the user's userid as + a principal, but this is not strictly necessary in custom policies that + define their principals differently. authorization policy An authorization policy in :app:`Pyramid` terms is a bit of -- cgit v1.2.3 From 48738dc116f9916356ac1d41029c3682b978a4ed Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 30 Jan 2016 18:04:49 -0800 Subject: add instructions for enabling pylons_sphinx_latesturl on previously released branch when making a new major release --- docs/conf.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'docs') diff --git a/docs/conf.py b/docs/conf.py index 4cac1e913..1004e1cf9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -55,6 +55,8 @@ extensions = [ 'sphinx.ext.viewcode', 'sphinx.ext.intersphinx', 'sphinxcontrib.programoutput', + # enable pylons_sphinx_latesturl when this branch is no longer "latest" + # 'pylons_sphinx_latesturl', ] # Looks for objects in external projects @@ -124,6 +126,21 @@ if book: # Options for HTML output # ----------------------- +# enable pylons_sphinx_latesturl when this branch is no longer "latest" +# pylons_sphinx_latesturl_base = ( +# 'http://docs.pylonsproject.org/projects/pyramid/en/latest/') +# pylons_sphinx_latesturl_pagename_overrides = { +# # map old pagename -> new pagename +# 'whatsnew-1.0': 'index', +# 'whatsnew-1.1': 'index', +# 'whatsnew-1.2': 'index', +# 'whatsnew-1.3': 'index', +# 'whatsnew-1.4': 'index', +# 'whatsnew-1.5': 'index', +# 'tutorials/gae/index': 'index', +# 'api/chameleon_text': 'api', +# 'api/chameleon_zpt': 'api', +# } html_theme = 'pyramid' html_theme_path = pylons_sphinx_themes.get_html_themes_path() -- cgit v1.2.3 From 7045a9a29c06bba453381463d46752ffb261ee73 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Mon, 1 Feb 2016 01:18:10 -0800 Subject: minor grammar, "simpler traversal machinery" --- docs/designdefense.rst | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 2da10108a..19d4fc49f 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -941,7 +941,7 @@ the same identity. Here's why they have a separate identity. .. _simpler_traversal_model: -Pyramid has Simpler Traversal Machinery than Does Zope +Pyramid has simpler traversal machinery than does Zope ------------------------------------------------------ Zope's default traverser: @@ -951,26 +951,26 @@ Zope's default traverser: - Attempts to use an adaptation to obtain the next element in the path from the currently traversed object, falling back to ``__bobo_traverse__``, - ``__getitem__`` and eventually ``__getattr__``. + ``__getitem__``, and eventually ``__getattr__``. Zope's default traverser allows developers to mutate the traversal name stack -during traversal by mutating ``REQUEST['TraversalNameStack']``. Pyramid's -default traverser (``pyramid.traversal.ResourceTreeTraverser``) does not -offer a way to do this; it does not maintain a stack as a request attribute -and, even if it did, it does not pass the request to resource objects while -it's traversing. While it was handy at times, this feature was abused in -frameworks built atop Zope (like CMF and Plone), often making it difficult to -tell exactly what was happening when a traversal didn't match a view. I felt -it was better to make folks that wanted the feature replace the traverser -rather than build that particular honey pot in to the default traverser. +during traversal by mutating ``REQUEST['TraversalNameStack']``. Pyramid's +default traverser (``pyramid.traversal.ResourceTreeTraverser``) does not offer +a way to do this. It does not maintain a stack as a request attribute and, even +if it did, it does not pass the request to resource objects while it's +traversing. While it was handy at times, this feature was abused in frameworks +built atop Zope (like CMF and Plone), often making it difficult to tell exactly +what was happening when a traversal didn't match a view. I felt it was better +for folks that wanted the feature to make them replace the traverser rather +than build that particular honey pot in to the default traverser. Zope uses multiple mechanisms to attempt to obtain the next element in the resource tree based on a name. It first tries an adaptation of the current -resource to ``ITraversable``, and if that fails, it falls back to attempting +resource to ``ITraversable``, and if that fails, it falls back to attempting a number of magic methods on the resource (``__bobo_traverse__``, -``__getitem__``, and ``__getattr__``). My experience while both using Zope -and attempting to reimplement its publisher in ``repoze.zope2`` led me to -believe the following: +``__getitem__``, and ``__getattr__``). My experience while both using Zope and +attempting to reimplement its publisher in ``repoze.zope2`` led me to believe +the following: - The *default* traverser should be as simple as possible. Zope's publisher is somewhat difficult to follow and replicate due to the fallbacks it tried @@ -991,7 +991,7 @@ believe the following: default implementation of the larger component, no one understands when (or whether) they should ever override the larger component entrirely. This results, over time, in a rusting together of the larger "replaceable" - component and the framework itself, because people come to depend on the + component and the framework itself because people come to depend on the availability of the default component in order just to turn its knobs. The default component effectively becomes part of the framework, which entirely subverts the goal of making it replaceable. In Pyramid, typically if a @@ -1000,6 +1000,7 @@ believe the following: you will replace the component instead of turning knobs attached to the component. + .. _microframeworks_smaller_hello_world: Microframeworks Have Smaller Hello World Programs -- cgit v1.2.3 From ed5209f2bdbb7bc8c54488cea97a0274af44be58 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sat, 6 Feb 2016 01:30:28 -0800 Subject: minor grammar and punctuation --- docs/designdefense.rst | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index 19d4fc49f..bc4e6fcfd 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -1003,31 +1003,32 @@ the following: .. _microframeworks_smaller_hello_world: -Microframeworks Have Smaller Hello World Programs +Microframeworks have smaller Hello World programs ------------------------------------------------- -Self-described "microframeworks" exist: `Bottle `_ and -`Flask `_ are two that are becoming popular. `Bobo -`_ doesn't describe itself as a microframework, -but its intended userbase is much the same. Many others exist. We've -actually even (only as a teaching tool, not as any sort of official project) -`created one using Pyramid `_ (the -videos use BFG, a precursor to Pyramid, but the resulting code is `available -for Pyramid too `_). Microframeworks are -small frameworks with one common feature: each allows its users to create a -fully functional application that lives in a single Python file. +Self-described "microframeworks" exist. `Bottle `_ and +`Flask `_ are two that are becoming popular. `Bobo +`_ doesn't describe itself as a microframework, but +its intended user base is much the same. Many others exist. We've even (only as +a teaching tool, not as any sort of official project) `created one using +Pyramid `_. The videos use BFG, a +precursor to Pyramid, but the resulting code is `available for Pyramid too +`_). Microframeworks are small frameworks +with one common feature: each allows its users to create a fully functional +application that lives in a single Python file. Some developers and microframework authors point out that Pyramid's "hello -world" single-file program is longer (by about five lines) than the -equivalent program in their favorite microframework. Guilty as charged. - -This loss isn't for lack of trying. Pyramid is useful in the same -circumstance in which microframeworks claim dominance: single-file -applications. But Pyramid doesn't sacrifice its ability to credibly support -larger applications in order to achieve hello-world LoC parity with the -current crop of microframeworks. Pyramid's design instead tries to avoid -some common pitfalls associated with naive declarative configuration schemes. -The subsections which follow explain the rationale. +world" single-file program is longer (by about five lines) than the equivalent +program in their favorite microframework. Guilty as charged. + +This loss isn't for lack of trying. Pyramid is useful in the same circumstance +in which microframeworks claim dominance: single-file applications. But Pyramid +doesn't sacrifice its ability to credibly support larger applications in order +to achieve "hello world" lines of code parity with the current crop of +microframeworks. Pyramid's design instead tries to avoid some common pitfalls +associated with naive declarative configuration schemes. The subsections which +follow explain the rationale. + .. _you_dont_own_modulescope: -- cgit v1.2.3 From 46f74df66cd940b8ed8b2cd0607f3eb4d8b65948 Mon Sep 17 00:00:00 2001 From: Steve Piercy Date: Sun, 7 Feb 2016 01:04:38 -0800 Subject: minor grammar and punctuation through "import-time side-effects are evil" --- docs/designdefense.rst | 146 ++++++++++++++++++++++++------------------------- 1 file changed, 72 insertions(+), 74 deletions(-) (limited to 'docs') diff --git a/docs/designdefense.rst b/docs/designdefense.rst index bc4e6fcfd..d33ae2fd8 100644 --- a/docs/designdefense.rst +++ b/docs/designdefense.rst @@ -1032,10 +1032,10 @@ follow explain the rationale. .. _you_dont_own_modulescope: -Application Programmers Don't Control The Module-Scope Codepath (Import-Time Side-Effects Are Evil) +Application programmers don't control the module-scope codepath (import-time side-effects are evil) +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ -Please imagine a directory structure with a set of Python files in it: +Imagine a directory structure with a set of Python files in it: .. code-block:: text @@ -1083,13 +1083,13 @@ The contents of ``config.py``: L.append(func) return func -If we cd to the directory that holds these files and we run ``python app.py`` -given the directory structure and code above, what happens? Presumably, our -``decorator`` decorator will be used twice, once by the decorated function -``foo`` in ``app.py`` and once by the decorated function ``bar`` in -``app2.py``. Since each time the decorator is used, the list ``L`` in -``config.py`` is appended to, we'd expect a list with two elements to be -printed, right? Sadly, no: +If we ``cd`` to the directory that holds these files, and we run +``python app.py``, given the directory structure and code above, what happens? +Presumably, our ``decorator`` decorator will be used twice, once by the +decorated function ``foo`` in ``app.py``, and once by the decorated function +``bar`` in ``app2.py``. Since each time the decorator is used, the list ``L`` +in ``config.py`` is appended to, we'd expect a list with two elements to be +printed, right? Sadly, no: .. code-block:: text @@ -1099,21 +1099,21 @@ printed, right? Sadly, no: ] By visual inspection, that outcome (three different functions in the list) -seems impossible. We only defined two functions and we decorated each of -those functions only once, so we believe that the ``decorator`` decorator -will only run twice. However, what we believe is wrong because the code at -module scope in our ``app.py`` module was *executed twice*. The code is +seems impossible. We defined only two functions, and we decorated each of those +functions only once, so we believe that the ``decorator`` decorator will run +only twice. However, what we believe is in fact wrong, because the code at +module scope in our ``app.py`` module was *executed twice*. The code is executed once when the script is run as ``__main__`` (via ``python app.py``), and then it is executed again when ``app2.py`` imports the same file as ``app``. -What does this have to do with our comparison to microframeworks? Many -microframeworks in the current crop (e.g. Bottle, Flask) encourage you to -attach configuration decorators to objects defined at module scope. These -decorators execute arbitrarily complex registration code which populates a -singleton registry that is a global defined in external Python module. This -is analogous to the above example: the "global registry" in the above example -is the list ``L``. +What does this have to do with our comparison to microframeworks? Many +microframeworks in the current crop (e.g., Bottle and Flask) encourage you to +attach configuration decorators to objects defined at module scope. These +decorators execute arbitrarily complex registration code, which populates a +singleton registry that is a global which is in turn defined in external Python +module. This is analogous to the above example: the "global registry" in the +above example is the list ``L``. Let's see what happens when we use the same pattern with the `Groundhog `_ microframework. Replace the contents @@ -1166,41 +1166,39 @@ will be. The encouragement to use decorators which perform population of an external registry has an unintended consequence: the application developer now must -assert ownership of every codepath that executes Python module scope -code. Module-scope code is presumed by the current crop of decorator-based -microframeworks to execute once and only once; if it executes more than once, -weird things will start to happen. It is up to the application developer to -maintain this invariant. Unfortunately, however, in reality, this is an -impossible task, because, Python programmers *do not own the module scope -codepath, and never will*. Anyone who tries to sell you on the idea that -they do is simply mistaken. Test runners that you may want to use to run -your code's tests often perform imports of arbitrary code in strange orders -that manifest bugs like the one demonstrated above. API documentation -generation tools do the same. Some people even think it's safe to use the -Python ``reload`` command or delete objects from ``sys.modules``, each of -which has hilarious effects when used against code that has import-time side -effects. - -Global-registry-mutating microframework programmers therefore will at some -point need to start reading the tea leaves about what *might* happen if -module scope code gets executed more than once like we do in the previous -paragraph. When Python programmers assume they can use the module-scope -codepath to run arbitrary code (especially code which populates an external -registry), and this assumption is challenged by reality, the application -developer is often required to undergo a painful, meticulous debugging -process to find the root cause of an inevitably obscure symptom. The -solution is often to rearrange application import ordering or move an import -statement from module-scope into a function body. The rationale for doing so -can never be expressed adequately in the checkin message which accompanies -the fix and can't be documented succinctly enough for the benefit of the rest -of the development team so that the problem never happens again. It will -happen again, especially if you are working on a project with other people -who haven't yet internalized the lessons you learned while you stepped -through module-scope code using ``pdb``. This is a really pretty poor -situation to find yourself in as an application developer: you probably -didn't even know your or your team signed up for the job, because the -documentation offered by decorator-based microframeworks don't warn you about -it. +assert ownership of every code path that executes Python module scope code. +Module-scope code is presumed by the current crop of decorator-based +microframeworks to execute once and only once. If it executes more than once, +weird things will start to happen. It is up to the application developer to +maintain this invariant. Unfortunately, in reality this is an impossible task, +because Python programmers *do not own the module scope code path, and never +will*. Anyone who tries to sell you on the idea that they do so is simply +mistaken. Test runners that you may want to use to run your code's tests often +perform imports of arbitrary code in strange orders that manifest bugs like the +one demonstrated above. API documentation generation tools do the same. Some +people even think it's safe to use the Python ``reload`` command, or delete +objects from ``sys.modules``, each of which has hilarious effects when used +against code that has import-time side effects. + +Global registry-mutating microframework programmers therefore will at some +point need to start reading the tea leaves about what *might* happen if module +scope code gets executed more than once, like we do in the previous paragraph. +When Python programmers assume they can use the module-scope code path to run +arbitrary code (especially code which populates an external registry), and this +assumption is challenged by reality, the application developer is often +required to undergo a painful, meticulous debugging process to find the root +cause of an inevitably obscure symptom. The solution is often to rearrange +application import ordering, or move an import statement from module-scope into +a function body. The rationale for doing so can never be expressed adequately +in the commit message which accompanies the fix, and can't be documented +succinctly enough for the benefit of the rest of the development team so that +the problem never happens again. It will happen again, especially if you are +working on a project with other people who haven't yet internalized the lessons +you learned while you stepped through module-scope code using ``pdb``. This is +a very poor situation in which to find yourself as an application developer: +you probably didn't even know you or your team signed up for the job, because +the documentation offered by decorator-based microframeworks don't warn you +about it. Folks who have a large investment in eager decorator-based configuration that populates an external data structure (such as microframework authors) may @@ -1216,7 +1214,7 @@ time, and application complexity. If microframework authors do admit that the circumstance isn't contrived, they might then argue that real damage will never happen as the result of the -double-execution (or triple-execution, etc) of module scope code. You would +double-execution (or triple-execution, etc.) of module scope code. You would be wise to disbelieve this assertion. The potential outcomes of multiple execution are too numerous to predict because they involve delicate relationships between application and framework code as well as chronology of @@ -1224,14 +1222,14 @@ code execution. It's literally impossible for a framework author to know what will happen in all circumstances. But even if given the gift of omniscience for some limited set of circumstances, the framework author almost certainly does not have the double-execution anomaly in mind when -coding new features. He's thinking of adding a feature, not protecting +coding new features. They're thinking of adding a feature, not protecting against problems that might be caused by the 1% multiple execution case. However, any 1% case may cause 50% of your pain on a project, so it'd be nice -if it never occured. +if it never occurred. -Responsible microframeworks actually offer a back-door way around the -problem. They allow you to disuse decorator based configuration entirely. -Instead of requiring you to do the following: +Responsible microframeworks actually offer a back-door way around the problem. +They allow you to disuse decorator-based configuration entirely. Instead of +requiring you to do the following: .. code-block:: python :linenos: @@ -1245,7 +1243,7 @@ Instead of requiring you to do the following: if __name__ == '__main__': gh.run() -They allow you to disuse the decorator syntax and go almost-all-imperative: +They allow you to disuse the decorator syntax and go almost all-imperative: .. code-block:: python :linenos: @@ -1269,18 +1267,18 @@ predictability. .. note:: - Astute readers may notice that Pyramid has configuration decorators too. - Aha! Don't these decorators have the same problems? No. These decorators - do not populate an external Python module when they are executed. They - only mutate the functions (and classes and methods) they're attached to. - These mutations must later be found during a scan process that has a - predictable and structured import phase. Module-localized mutation is - actually the best-case circumstance for double-imports; if a module only - mutates itself and its contents at import time, if it is imported twice, - that's OK, because each decorator invocation will always be mutating an - independent copy of the object it's attached to, not a shared resource like - a registry in another module. This has the effect that - double-registrations will never be performed. + Astute readers may notice that Pyramid has configuration decorators too. Aha! + Don't these decorators have the same problems? No. These decorators do not + populate an external Python module when they are executed. They only mutate + the functions (and classes and methods) to which they're attached. These + mutations must later be found during a scan process that has a predictable + and structured import phase. Module-localized mutation is actually the + best-case circumstance for double-imports. If a module only mutates itself + and its contents at import time, if it is imported twice, that's OK, because + each decorator invocation will always be mutating an independent copy of the + object to which it's attached, not a shared resource like a registry in + another module. This has the effect that double-registrations will never be + performed. .. _routes_need_ordering: -- cgit v1.2.3 From ed04017d5a8e82db2e46412f841c55d83ef062b0 Mon Sep 17 00:00:00 2001 From: Michael Merickel Date: Sun, 7 Feb 2016 14:00:20 -0600 Subject: fix pyramid_tm url --- docs/conf.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'docs') diff --git a/docs/conf.py b/docs/conf.py index 1004e1cf9..a895bc6c3 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -69,7 +69,7 @@ intersphinx_mapping = { 'python': ('http://docs.python.org', None), 'python3': ('http://docs.python.org/3', None), 'sqla': ('http://docs.sqlalchemy.org/en/latest', None), - 'tm': ('http://docs.pylonsproject.org/projects/pyramid_tm/en/latest/', None), + 'tm': ('http://docs.pylonsproject.org/projects/pyramid-tm/en/latest/', None), 'toolbar': ('http://docs.pylonsproject.org/projects/pyramid-debugtoolbar/en/latest', None), 'tstring': ('http://docs.pylonsproject.org/projects/translationstring/en/latest', None), 'tutorials': ('http://docs.pylonsproject.org/projects/pyramid-tutorials/en/latest/', None), -- cgit v1.2.3