diff options
| author | Chris McDonough <chrism@plope.com> | 2011-01-18 10:39:24 -0500 |
|---|---|---|
| committer | Chris McDonough <chrism@plope.com> | 2011-01-18 10:39:24 -0500 |
| commit | c1eb0c69f2067baa567f68f6cc472397ec71f65a (patch) | |
| tree | 817e286ae8f700454c25b246ddaf1eada8067f30 | |
| parent | 566004501e8a28c0ba8f8c882ca5ea0742e5d285 (diff) | |
| download | pyramid-c1eb0c69f2067baa567f68f6cc472397ec71f65a.tar.gz pyramid-c1eb0c69f2067baa567f68f6cc472397ec71f65a.tar.bz2 pyramid-c1eb0c69f2067baa567f68f6cc472397ec71f65a.zip | |
- The ``make_app`` function has been removed from the ``pyramid.router``
module. It continues life within the ``pyramid_zcml`` package. This
leaves the ``pyramid.router`` module without any API functions.
- The ``configure_zcml`` setting within the deployment settings (within
``**settings`` passed to a Pyramid ``main`` function) has ceased to have any
meaning.
- The ``starter_zcml`` paster template has been moved to the ``pyramid_zcml``
package.
- The ``bfg2pyramid`` script now converts ZCML include tags that have
``repoze.bfg.includes`` as a package attribute to the value
``pyramid_zcml``. For example, ``<include package="repoze.bfg.includes">``
will be converted to ``<include package="pyramid_zcml">``.
- The ``load_zcml`` method of a Configurator has been removed from the
Pyramid core. Loading ZCML is now a feature of the ``pyramid_zcml``
package, which can be downloaded from PyPI. Documentation for the package
should be available via http://pylonsproject.org, which describes how to
get this method back after depending upon ``pyramid_zcml`` as an
``install_requires`` dependency.
- The ``pyramid.includes`` subpackage has been removed. ZCML files which use
include the package ``pyramid.includes`` (e.g. ``<include
package="pyramid.includes">``) now must include the ``pyramid_zcml``
package instead (e.g. ``<include package="pyramid_zcml"/>).
- The "Declarative Configuration" narrative chapter has been removed (it was
moved to the ``pyramid_zcml`` pakcage).
- The add_directive method now accepts an "action_wrap" flag.
- Fix some orphaned references.
- Remove some docstring references to ZCML directives.
- All integration test fixtures have been changed to use imperative
configuration rather than ZCML configuration.
70 files changed, 169 insertions, 4612 deletions
diff --git a/CHANGES.txt b/CHANGES.txt index 67562fbd6..ac020b4b1 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -29,6 +29,17 @@ Backwards Incompatibilities templates were removed. Use ``pyramid_sqla`` (available from PyPI) as a generic replacement for Pylons-esque development. +- The ``make_app`` function has been removed from the ``pyramid.router`` + module. It continues life within the ``pyramid_zcml`` package. This + leaves the ``pyramid.router`` module without any API functions. + +- The ``configure_zcml`` setting within the deployment settings (within + ``**settings`` passed to a Pyramid ``main`` function) has ceased to have any + meaning. + +- The ``starter_zcml`` paster template has been moved to the ``pyramid_zcml`` + package. + Features -------- @@ -51,6 +62,11 @@ Features ``config.include('some.module.somefunc')`` as long as the include function within ``some.module`` is named ``includeme``. +- The ``bfg2pyramid`` script now converts ZCML include tags that have + ``repoze.bfg.includes`` as a package attribute to the value + ``pyramid_zcml``. For example, ``<include package="repoze.bfg.includes">`` + will be converted to ``<include package="pyramid_zcml">``. + Paster Templates ---------------- diff --git a/docs/api.rst b/docs/api.rst index b650c8ded..be7942502 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -24,7 +24,6 @@ documentation is organized alphabetically by module name. api/renderers api/request api/response - api/router api/scripting api/security api/session diff --git a/docs/api/config.rst b/docs/api/config.rst index b4f85c248..05bcb8146 100644 --- a/docs/api/config.rst +++ b/docs/api/config.rst @@ -52,8 +52,6 @@ .. automethod:: derive_view - .. automethod:: load_zcml(spec) - .. automethod:: make_wsgi_app() .. automethod:: override_asset(to_override, override_with) diff --git a/docs/api/router.rst b/docs/api/router.rst deleted file mode 100644 index e5ffe97ce..000000000 --- a/docs/api/router.rst +++ /dev/null @@ -1,8 +0,0 @@ -.. _router_module: - -:mod:`pyramid.router` ---------------------- - -.. automodule:: pyramid.router - -.. autofunction:: pyramid.router.make_app(root_factory, package=None, filename='configure.zcml', settings=None) diff --git a/docs/index.rst b/docs/index.rst index 0dc476e46..e0a0db214 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -58,7 +58,6 @@ Narrative documentation in chapter form explaining how to use narr/testing narr/hooks narr/advconfig - narr/declarative narr/extending narr/router narr/threadlocals diff --git a/docs/latexindex.rst b/docs/latexindex.rst index 00f177e5c..a8232651b 100644 --- a/docs/latexindex.rst +++ b/docs/latexindex.rst @@ -51,9 +51,7 @@ Narrative Documentation narr/testing narr/hooks narr/advconfig - narr/declarative narr/extending - narr/router narr/startup narr/threadlocals narr/zca diff --git a/docs/narr/declarative.rst b/docs/narr/declarative.rst deleted file mode 100644 index 5c01ff491..000000000 --- a/docs/narr/declarative.rst +++ /dev/null @@ -1,1396 +0,0 @@ -.. _declarative_chapter: - -Declarative Configuration -========================= - -The mode of configuration detailed in the majority of examples within this -this book is "imperative" configuration. This is the configuration mode in -which a developer cedes the least amount of control to the framework; it's -"imperative" because you express the configuration directly in Python code, -and you have the full power of Python at your disposal as you issue -configuration statements. However, another mode of configuration exists -within :app:`Pyramid` named :term:`ZCML` which often provides better -opportunity for extensibility. - -A complete listing of ZCML directives is available within -:ref:`zcml_directives`. This chapter provides an overview of how you might -get started with ZCML and highlights some common tasks performed when you use -ZCML. - -.. index:: - single: declarative configuration - -.. _declarative_configuration: - -ZCML Configuration ------------------- - -A :app:`Pyramid` application can be configured "declaratively", if so -desired. Declarative configuration relies on *declarations* made external to -the code in a configuration file format named :term:`ZCML` (Zope -Configuration Markup Language), an XML dialect. - -A :app:`Pyramid` application configured declaratively requires not -one, but two files: a Python file and a :term:`ZCML` file. - -In a file named ``helloworld.py``: - -.. code-block:: python - :linenos: - - from paste.httpserver import serve - from pyramid.response import Response - from pyramid.config import Configurator - - def hello_world(request): - return Response('Hello world!') - - if __name__ == '__main__': - config = Configurator() - config.load_zcml('configure.zcml') - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -In a file named ``configure.zcml`` in the same directory as the -previously created ``helloworld.py``: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view="helloworld.hello_world" - /> - - </configure> - -This pair of files forms an application functionally equivalent to the -application we created earlier in :ref:`imperative_configuration`. -Let's examine the differences between that code listing and the code -above. - -In :ref:`imperative_configuration`, we had the following lines within -the ``if __name__ == '__main__'`` section of ``helloworld.py``: - -.. code-block:: python - :linenos: - - if __name__ == '__main__': - config = Configurator() - config.add_view(hello_world) - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -In our "declarative" code, we've removed the call to ``add_view`` and -replaced it with a call to the -:meth:`pyramid.config.Configurator.load_zcml` method so that -it now reads as: - -.. code-block:: python - :linenos: - - if __name__ == '__main__': - config = Configurator() - config.load_zcml('configure.zcml') - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -Everything else is much the same. - -The ``config.load_zcml('configure.zcml')`` line tells the configurator -to load configuration declarations from the file named -``configure.zcml`` which sits next to ``helloworld.py`` on the -filesystem. Let's take a look at that ``configure.zcml`` file again: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view="helloworld.hello_world" - /> - - </configure> - -Note that this file contains some XML, and that the XML contains a -``<view>`` :term:`configuration declaration` tag that references a -:term:`dotted Python name`. This dotted name refers to the -``hello_world`` function that lives in our ``helloworld`` Python -module. - -This ``<view>`` declaration tag performs the same function as the -``add_view`` method that was employed within -:ref:`imperative_configuration`. In fact, the ``<view>`` tag is -effectively a "macro" which calls the -:meth:`pyramid.config.Configurator.add_view` method on your -behalf. - -The ``<view>`` tag is an example of a :app:`Pyramid` declaration -tag. Other such tags include ``<route>`` and ``<scan>``. Each of -these tags is effectively a "macro" which calls methods of a -:class:`pyramid.config.Configurator` object on your behalf. - -Essentially, using a :term:`ZCML` file and loading it from the -filesystem allows us to put our configuration statements within this -XML file rather as declarations, rather than representing them as -method calls to a :term:`Configurator` object. Otherwise, declarative -and imperative configuration are functionally equivalent. - -Using declarative configuration has a number of benefits, the primary -benefit being that applications configured declaratively can be -*overridden* and *extended* by third parties without requiring the -third party to change application code. If you want to build a -framework or an extensible application, using declarative -configuration is a good idea. - -Declarative configuration has an obvious downside: you can't use -plain-old-Python syntax you probably already know and understand to -configure your application; instead you need to use :term:`ZCML`. - -.. index:: - single: ZCML conflict detection - -.. _zcml_conflict_detection: - -ZCML Conflict Detection -~~~~~~~~~~~~~~~~~~~~~~~ - -A minor additional feature of ZCML is *conflict detection*. If you -define two declaration tags within the same ZCML file which logically -"collide", an exception will be raised, and the application will not -start. For example, the following ZCML file has two conflicting -``<view>`` tags: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view="helloworld.hello_world" - /> - - <view - view="helloworld.hello_world" - /> - - </configure> - -If you try to use this ZCML file as the source of ZCML for an -application, an error will be raised when you attempt to start the -application. This error will contain information about which tags -might have conflicted. - -.. index:: - single: helloworld (declarative) - -.. _helloworld_declarative: - -Hello World, Goodbye World (Declarative) ----------------------------------------- - -Another almost entirely equivalent mode of application configuration -exists named *declarative* configuration. :app:`Pyramid` can be -configured for the same "hello world" application "declaratively", if -so desired. - -To do so, first, create a file named ``helloworld.py``: - -.. code-block:: python - :linenos: - - from pyramid.config import Configurator - from pyramid.response import Response - from paste.httpserver import serve - - def hello_world(request): - return Response('Hello world!') - - def goodbye_world(request): - return Response('Goodbye world!') - - if __name__ == '__main__': - config = Configurator() - config.load_zcml('configure.zcml') - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -Then create a file named ``configure.zcml`` in the same directory as -the previously created ``helloworld.py``: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view="helloworld.hello_world" - /> - - <view - name="goodbye" - view="helloworld.goodbye_world" - /> - - </configure> - -This pair of files forms an application functionally equivalent to the -application we created earlier in :ref:`helloworld_imperative`. We can run -it the same way. - -.. code-block:: text - - $ python helloworld.py - serving on 0.0.0.0:8080 view at http://127.0.0.1:8080 - -Let's examine the differences between the code in that section and the code -above. In :ref:`helloworld_imperative_appconfig`, we had the following lines -within the ``if __name__ == '__main__'`` section of ``helloworld.py``: - -.. code-block:: python - :linenos: - - if __name__ == '__main__': - config = Configurator() - config.add_view(hello_world) - config.add_view(goodbye_world, name='goodbye') - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -In our "declarative" code, we've added a call to the -:meth:`pyramid.config.Configurator.load_zcml` method with -the value ``configure.zcml``, and we've removed the lines which read -``config.add_view(hello_world)`` and ``config.add_view(goodbye_world, -name='goodbye')``, so that it now reads as: - -.. code-block:: python - :linenos: - - if __name__ == '__main__': - config = Configurator() - config.load_zcml('configure.zcml') - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -Everything else is much the same. - -The ``config.load_zcml('configure.zcml')`` line tells the configurator -to load configuration declarations from the ``configure.zcml`` file -which sits next to ``helloworld.py``. Let's take a look at the -``configure.zcml`` file now: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view="helloworld.hello_world" - /> - - <view - name="goodbye" - view="helloworld.goodbye_world" - /> - - </configure> - -We already understand what the view code does, because the application -is functionally equivalent to the application described in -:ref:`helloworld_imperative`, but use of :term:`ZCML` is new. Let's -break that down tag-by-tag. - -The ``<configure>`` Tag -~~~~~~~~~~~~~~~~~~~~~~~ - -The ``configure.zcml`` ZCML file contains this bit of XML: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <!-- other directives --> - - </configure> - -Because :term:`ZCML` is XML, and because XML requires a single root -tag for each document, every ZCML file used by :app:`Pyramid` must -contain a ``configure`` container directive, which acts as the root -XML tag. It is a "container" directive because its only job is to -contain other directives. - -See also :ref:`configure_directive` and :ref:`word_on_xml_namespaces`. - -.. _the_include_tag: - -The ``<include>`` Tag -~~~~~~~~~~~~~~~~~~~~~ - -The ``configure.zcml`` ZCML file contains this bit of XML within the -``<configure>`` root tag: - -.. code-block:: xml - :linenos: - - <include package="pyramid.includes" /> - -This self-closing tag instructs :app:`Pyramid` to load a ZCML file -from the Python package with the :term:`dotted Python name` -``pyramid.includes``, as specified by its ``package`` attribute. -This particular ``<include>`` declaration is required because it -actually allows subsequent declaration tags (such as ``<view>``, which -we'll see shortly) to be recognized. The ``<include>`` tag -effectively just includes another ZCML file, causing its declarations -to be executed. In this case, we want to load the declarations from -the file named ``configure.zcml`` within the -:mod:`pyramid.includes` Python package. We know we want to load -the ``configure.zcml`` from this package because ``configure.zcml`` is -the default value for another attribute of the ``<include>`` tag named -``file``. We could have spelled the include tag more verbosely, but -equivalently as: - -.. code-block:: xml - :linenos: - - <include package="pyramid.includes" - file="configure.zcml"/> - -The ``<include>`` tag that includes the ZCML statements implied by the -``configure.zcml`` file from the Python package named -:mod:`pyramid.includes` is basically required to come before any -other named declaration in an application's ``configure.zcml``. If it -is not included, subsequent declaration tags will fail to be -recognized, and the configuration system will generate an error at -startup. However, the ``<include package="pyramid.includes"/>`` -tag needs to exist only in a "top-level" ZCML file, it needn't also -exist in ZCML files *included by* a top-level ZCML file. - -See also :ref:`include_directive`. - -The ``<view>`` Tag -~~~~~~~~~~~~~~~~~~ - -The ``configure.zcml`` ZCML file contains these bits of XML *after* the -``<include>`` tag, but *within* the ``<configure>`` root tag: - -.. code-block:: xml - :linenos: - - <view - view="helloworld.hello_world" - /> - - <view - name="goodbye" - view="helloworld.goodbye_world" - /> - -These ``<view>`` declaration tags direct :app:`Pyramid` to create -two :term:`view configuration` registrations. The first ``<view>`` -tag has an attribute (the attribute is also named ``view``), which -points at a :term:`dotted Python name`, referencing the -``hello_world`` function defined within the ``helloworld`` package. -The second ``<view>`` tag has a ``view`` attribute which points at a -:term:`dotted Python name`, referencing the ``goodbye_world`` function -defined within the ``helloworld`` package. The second ``<view>`` tag -also has an attribute called ``name`` with a value of ``goodbye``. - -These effect of the ``<view>`` tag declarations we've put into our -``configure.zcml`` is functionally equivalent to the effect of lines -we've already seen in an imperatively-configured application. We're -just spelling things differently, using XML instead of Python. - -In our previously defined application, in which we added view -configurations imperatively, we saw this code: - -.. ignore-next-block -.. code-block:: python - :linenos: - - config.add_view(hello_world) - config.add_view(goodbye_world, name='goodbye') - -Each ``<view>`` declaration tag encountered in a ZCML file effectively -invokes the :meth:`pyramid.config.Configurator.add_view` -method on the behalf of the developer. Various attributes can be -specified on the ``<view>`` tag which influence the :term:`view -configuration` it creates. - -Since the relative ordering of calls to -:meth:`pyramid.config.Configurator.add_view` doesn't matter -(see the sidebar entitled *View Dispatch and Ordering* within -:ref:`adding_configuration`), the relative order of ``<view>`` tags in -ZCML doesn't matter either. The following ZCML orderings are -completely equivalent: - -.. topic:: Hello Before Goodbye - - .. code-block:: xml - :linenos: - - <view - view="helloworld.hello_world" - /> - - <view - name="goodbye" - view="helloworld.goodbye_world" - /> - -.. topic:: Goodbye Before Hello - - .. code-block:: xml - :linenos: - - <view - name="goodbye" - view="helloworld.goodbye_world" - /> - - <view - view="helloworld.hello_world" - /> - -We've now configured a :app:`Pyramid` helloworld application -declaratively. More information about this mode of configuration is -available in :ref:`declarative_configuration` and within -:ref:`zcml_reference`. - -.. index:: - single: ZCML granularity - -ZCML Granularity -~~~~~~~~~~~~~~~~ - -It's extremely helpful to third party application "extenders" (aka -"integrators") if the :term:`ZCML` that composes the configuration for an -application is broken up into separate files which do very specific things. -These more specific ZCML files can be reintegrated within the application's -main ``configure.zcml`` via ``<include file="otherfile.zcml"/>`` -declarations. When ZCML files contain sets of specific declarations, an -integrator can avoid including any ZCML he does not want by including only -ZCML files which contain the declarations he needs. He is not forced to -"accept everything" or "use nothing". - -For example, it's often useful to put all ``<route>`` declarations in a -separate ZCML file, as ``<route>`` statements have a relative ordering that -is extremely important to the application: if an extender wants to add a -route to the "middle" of the routing table, he will always need to disuse all -the routes and cut and paste the routing configuration into his own -application. It's useful for the extender to be able to disuse just a -*single* ZCML file in this case, accepting the remainder of the configuration -from other :term:`ZCML` files in the original application. - -Granularizing ZCML is not strictly required. An extender can always disuse -*all* your ZCML, choosing instead to copy and paste it into his own package, -if necessary. However, doing so is considerate, and allows for the best -reusability. Sometimes it's possible to include only certain ZCML files from -an application that contain only the registrations you really need, omitting -others. But sometimes it's not. For brute force purposes, when you're -getting ``view`` or ``route`` registrations that you don't actually want in -your overridden application, it's always appropriate to just *not include* -any ZCML file from the overridden application. Instead, just cut and paste -the entire contents of the ``configure.zcml`` (and any ZCML file included by -the overridden application's ``configure.zcml``) into your own package and -omit the ``<include package=""/>`` ZCML declaration in the overriding -package's ``configure.zcml``. - -.. _zcml_scanning: - -Scanning via ZCML ------------------ - -:term:`ZCML` can invoke a :term:`scan` via its ``<scan>`` directive. If a -ZCML file is processed that contains a scan directive, the package the ZCML -file points to is scanned. - -.. code-block:: python - :linenos: - - # helloworld.py - - from paste.httpserver import serve - from pyramid.response import Response - from pyramid.view import view_config - - @view_config() - def hello(request): - return Response('Hello') - - if __name__ == '__main__': - from pyramid.config import Configurator - config = Configurator() - config.load_zcml('configure.zcml') - app = config.make_wsgi_app() - serve(app, host='0.0.0.0') - -.. code-block:: xml - :linenos: - - <configure xmlns="http://namespaces.repoze.org"> - - <!-- configure.zcml --> - - <include package="pyramid.includes"/> - <scan package="."/> - - </configure> - -See also :ref:`scan_directive`. - -Which Mode Should I Use? ------------------------- - -A combination of imperative configuration, declarative configuration -via ZCML and scanning can be used to configure any application. They -are not mutually exclusive. - -The :app:`Pyramid` authors often recommend using mostly declarative -configuration, because it's the more traditional form of configuration -used in :app:`Pyramid` applications, it can be overridden and -extended by third party deployers, and there are more examples for it -"in the wild". - -However, imperative mode configuration can be simpler to understand, -and the framework is not "opinionated" about the choice. This book -presents examples in both styles, mostly interchangeably. You can -choose the mode that best fits your brain as necessary. - -.. index:: - single: ZCML view configuration - -.. _mapping_views_using_zcml_section: - -View Configuration Via ZCML -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You may associate a view with a URL by adding :ref:`view_directive` -declarations via :term:`ZCML` in a ``configure.zcml`` file. An -example of a view declaration in ZCML is as follows: - -.. code-block:: xml - :linenos: - - <view - context=".resources.Hello" - view=".views.hello_world" - name="hello.html" - /> - -The above maps the ``.views.hello_world`` view callable function to -the following set of :term:`resource location` results: - -- A :term:`context` object which is an instance (or subclass) of the - Python class represented by ``.resources.Hello`` - -- A :term:`view name` equalling ``hello.html``. - -.. note:: Values prefixed with a period (``.``) for the ``context`` - and ``view`` attributes of a ``view`` declaration (such as those - above) mean "relative to the Python package directory in which this - :term:`ZCML` file is stored". So if the above ``view`` declaration - was made inside a ``configure.zcml`` file that lived in the - ``hello`` package, you could replace the relative ``.resources.Hello`` - with the absolute ``hello.resources.Hello``; likewise you could - replace the relative ``.views.hello_world`` with the absolute - ``hello.views.hello_world``. Either the relative or absolute form - is functionally equivalent. It's often useful to use the relative - form, in case your package's name changes. It's also shorter to - type. - -You can also declare a *default view callable* for a :term:`resource` type: - -.. code-block:: xml - :linenos: - - <view - context=".resources.Hello" - view=".views.hello_world" - /> - -A *default view callable* simply has no ``name`` attribute. For the above -registration, when a :term:`context` is found that is of the type -``.resources.Hello`` and there is no :term:`view name` associated with the -result of :term:`resource location`, the *default view callable* will be -used. In this case, it's the view at ``.views.hello_world``. - -A default view callable can alternately be defined by using the empty -string as its ``name`` attribute: - -.. code-block:: xml - :linenos: - - <view - context=".resources.Hello" - view=".views.hello_world" - name="" - /> - -You may also declare that a view callable is good for any context type -by using the special ``*`` character as the value of the ``context`` -attribute: - -.. code-block:: xml - :linenos: - - <view - context="*" - view=".views.hello_world" - name="hello.html" - /> - -This indicates that when :app:`Pyramid` identifies that the -:term:`view name` is ``hello.html`` and the context is of any type, -the ``.views.hello_world`` view callable will be invoked. - -A ZCML ``view`` declaration's ``view`` attribute can also name a -class. In this case, the rules described in :ref:`class_as_view` -apply for the class which is named. - -See :ref:`view_directive` for complete ZCML directive documentation. - -.. index:: - single: ZCML directive; route - -.. _zcml_route_configuration: - -Configuring a Route via ZCML ----------------------------- - -Instead of using the imperative :meth:`pyramid.config.Configurator.add_route` -method to add a new route, you can alternately use :term:`ZCML`. -:ref:`route_directive` statements in a :term:`ZCML` file. For example, the -following :term:`ZCML declaration` causes a route to be added to the -application. - -.. code-block:: xml - :linenos: - - <route - name="myroute" - pattern="/prefix/{one}/{two}" - view=".views.myview" - /> - -.. note:: - - Values prefixed with a period (``.``) within the values of ZCML - attributes such as the ``view`` attribute of a ``route`` mean - "relative to the Python package directory in which this - :term:`ZCML` file is stored". So if the above ``route`` - declaration was made inside a ``configure.zcml`` file that lived in - the ``hello`` package, you could replace the relative - ``.views.myview`` with the absolute ``hello.views.myview`` Either - the relative or absolute form is functionally equivalent. It's - often useful to use the relative form, in case your package's name - changes. It's also shorter to type. - -The order that routes are evaluated when declarative configuration is used -is the order that they appear relative to each other in the ZCML file. - -See :ref:`route_directive` for full ``route`` ZCML directive -documentation. - -.. index:: - triple: view; zcml; static resource - -.. _zcml_static_assets_section: - -Serving Static Assets Using ZCML --------------------------------- - -Use of the ``static`` ZCML directive makes static assets available at a name -relative to the application root URL, e.g. ``/static``. - -Note that the ``path`` provided to the ``static`` ZCML directive may be a -fully qualified :term:`asset specification`, a package-relative path, or -an *absolute path*. The ``path`` with the value ``a/b/c/static`` of a -``static`` directive in a ZCML file that resides in the "mypackage" package -will resolve to a package-qualified assets such as -``some_package:a/b/c/static``. - -Here's an example of a ``static`` ZCML directive that will serve files -up under the ``/static`` URL from the ``/var/www/static`` directory of -the computer which runs the :app:`Pyramid` application using an -absolute path. - -.. code-block:: xml - :linenos: - - <static - name="static" - path="/var/www/static" - /> - -Here's an example of a ``static`` directive that will serve files up -under the ``/static`` URL from the ``a/b/c/static`` directory of the -Python package named ``some_package`` using a fully qualified -:term:`asset specification`. - -.. code-block:: xml - :linenos: - - <static - name="static" - path="some_package:a/b/c/static" - /> - -Here's an example of a ``static`` directive that will serve files up -under the ``/static`` URL from the ``static`` directory of the Python -package in which the ``configure.zcml`` file lives using a -package-relative path. - -.. code-block:: xml - :linenos: - - <static - name="static" - path="static" - /> - -Whether you use for ``path`` a fully qualified asset specification, -an absolute path, or a package-relative path, When you place your -static files on the filesystem in the directory represented as the -``path`` of the directive, you will then be able to view the static -files in this directory via a browser at URLs prefixed with the -directive's ``name``. For instance if the ``static`` directive's -``name`` is ``static`` and the static directive's ``path`` is -``/path/to/static``, ``http://localhost:6543/static/foo.js`` will -return the file ``/path/to/static/dir/foo.js``. The static directory -may contain subdirectories recursively, and any subdirectories may -hold files; these will be resolved by the static view as you would -expect. - -While the ``path`` argument can be a number of different things, the -``name`` argument of the ``static`` ZCML directive can also be one of -a number of things: a *view name* or a *URL*. The above examples have -shown usage of the ``name`` argument as a view name. When ``name`` is -a *URL* (or any string with a slash (``/``) in it), static assets -can be served from an external webserver. In this mode, the ``name`` -is used as the URL prefix when generating a URL using -:func:`pyramid.url.static_url`. - -For example, the ``static`` ZCML directive may be fed a ``name`` -argument which is ``http://example.com/images``: - -.. code-block:: xml - :linenos: - - <static - name="http://example.com/images" - path="mypackage:images" - /> - -Because the ``static`` ZCML directive is provided with a ``name`` argument -that is the URL prefix ``http://example.com/images``, subsequent calls to -:func:`pyramid.url.static_url` with paths that start with the ``path`` -argument passed to :meth:`pyramid.url.static_url` will generate a URL -something like ``http://example.com/logo.png``. The external webserver -listening on ``example.com`` must be itself configured to respond properly to -such a request. The :func:`pyramid.url.static_url` API is discussed in more -detail later in this chapter. - -The :meth:`pyramid.config.Configurator.add_static_view` method offers -an imperative equivalent to the ``static`` ZCML directive. Use of the -``add_static_view`` imperative configuration method is completely equivalent -to using ZCML for the same purpose. See :ref:`static_assets_section` for -more information. - -.. index:: - pair: ZCML directive; asset - -.. _asset_zcml_directive: - -The ``asset`` ZCML Directive -~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Instead of using :meth:`pyramid.config.Configurator.override_asset` during -:term:`imperative configuration`, an equivalent ZCML directive can be used. -The ZCML ``asset`` tag is a frontend to using -:meth:`pyramid.config.Configurator.override_asset`. - -An individual :app:`Pyramid` ``asset`` ZCML statement can override a -single asset. For example: - -.. code-block:: xml - :linenos: - - <asset - to_override="some.package:templates/mytemplate.pt" - override_with="another.package:othertemplates/anothertemplate.pt" - /> - -The string value passed to both ``to_override`` and ``override_with`` -attached to an ``asset`` directive is called an "asset specification". The -colon separator in a specification separates the *package name* from the -*asset name*. The colon and the following asset name are optional. If they -are not specified, the override attempts to resolve every lookup into a -package from the directory of another package. For example: - -.. code-block:: xml - :linenos: - - <asset - to_override="some.package" - override_with="another.package" - /> - -Individual subdirectories within a package can also be overridden: - -.. code-block:: xml - :linenos: - - <asset - to_override="some.package:templates/" - override_with="another.package:othertemplates/" - /> - -If you wish to override an asset directory with another directory, you *must* -make sure to attach the slash to the end of both the ``to_override`` -specification and the ``override_with`` specification. If you fail to attach -a slash to the end of an asset specification that points to a directory, you -will get unexpected results. - -The package name in an asset specification may start with a dot, meaning that -the package is relative to the package in which the ZCML file resides. For -example: - -.. code-block:: xml - :linenos: - - <asset - to_override=".subpackage:templates/" - override_with="another.package:templates/" - /> - -See also :ref:`asset_directive`. - -.. _zcml_authorization_policy: - -Enabling an Authorization Policy Via ZCML ------------------------------------------ - -If you'd rather use :term:`ZCML` to specify an authorization policy -than imperative configuration, modify the ZCML file loaded by your -application (usually named ``configure.zcml``) to enable an -authorization policy. - -For example, to enable a policy which compares the value of an "auth ticket" -cookie passed in the request's environment which contains a reference to a -single :term:`principal` against the principals present in any :term:`ACL` -found in the resource tree when attempting to call some :term:`view`, modify -your ``configure.zcml`` to look something like this: - -.. code-block:: xml - :linenos: - - <configure xmlns="http://pylonshq.com/pyramid"> - - <!-- views and other directives before this... --> - - <authtktauthenticationpolicy - secret="iamsosecret"/> - - <aclauthorizationpolicy/> - - </configure> - -"Under the hood", these statements cause an instance of the class -:class:`pyramid.authentication.AuthTktAuthenticationPolicy` to be -injected as the :term:`authentication policy` used by this application -and an instance of the class -:class:`pyramid.authorization.ACLAuthorizationPolicy` to be -injected as the :term:`authorization policy` used by this application. - -:app:`Pyramid` ships with a number of authorization and -authentication policy ZCML directives that should prove useful. See -:ref:`authentication_policies_directives_section` and -:ref:`authorization_policies_directives_section` for more information. - -.. index:: - pair: ZCML directive; authentication policy - -.. _authentication_policies_directives_section: - -Built-In Authentication Policy ZCML Directives ----------------------------------------------- - -Instead of configuring an authentication policy and authorization -policy imperatively, :app:`Pyramid` ships with a few "pre-chewed" -authentication policy ZCML directives that you can make use of within -your application. - -``authtktauthenticationpolicy`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When this directive is used, authentication information is obtained -from an "auth ticket" cookie value, assumed to be set by a custom -login form. - -An example of its usage, with all attributes fully expanded: - -.. code-block:: xml - :linenos: - - <authtktauthenticationpolicy - secret="goshiamsosecret" - callback=".somemodule.somefunc" - cookie_name="mycookiename" - secure="false" - include_ip="false" - timeout="86400" - reissue_time="600" - max_age="31536000" - path="/" - http_only="false" - /> - -See :ref:`authtktauthenticationpolicy_directive` for details about -this directive. - -``remoteuserauthenticationpolicy`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When this directive is used, authentication information is obtained -from a ``REMOTE_USER`` key in the WSGI environment, assumed to -be set by a WSGI server or an upstream middleware component. - -An example of its usage, with all attributes fully expanded: - -.. code-block:: xml - :linenos: - - <remoteuserauthenticationpolicy - environ_key="REMOTE_USER" - callback=".somemodule.somefunc" - /> - -See :ref:`remoteuserauthenticationpolicy_directive` for detailed -information. - -``repozewho1authenticationpolicy`` -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -When this directive is used, authentication information is obtained -from a ``repoze.who.identity`` key in the WSGI environment, assumed to -be set by :term:`repoze.who` middleware. - -An example of its usage, with all attributes fully expanded: - -.. code-block:: xml - :linenos: - - <repozewho1authenticationpolicy - identifier_name="auth_tkt" - callback=".somemodule.somefunc" - /> - -See :ref:`repozewho1authenticationpolicy_directive` for detailed -information. - -.. index:: - pair: ZCML directive; authorization policy - -.. _authorization_policies_directives_section: - -Built-In Authorization Policy ZCML Directives ---------------------------------------------- - -``aclauthorizationpolicy`` - -When this directive is used, authorization information is obtained -from :term:`ACL` objects attached to resources. - -An example of its usage, with all attributes fully expanded: - -.. code-block:: xml - :linenos: - - <aclauthorizationpolicy/> - -In other words, it has no configuration attributes; its existence in a -``configure.zcml`` file enables it. - -See :ref:`aclauthorizationpolicy_directive` for detailed information. - -.. _zcml_adding_and_overriding_renderers: - -Adding and Changing Renderers via ZCML --------------------------------------- - -New templating systems and serializers can be associated with :app:`Pyramid` -renderer names. To this end, configuration declarations can be made which -change an existing :term:`renderer factory` and which add a new renderer -factory. - -Adding or changing an existing renderer via ZCML is accomplished via the -:ref:`renderer_directive` ZCML directive. - -For example, to add a renderer which renders views which have a -``renderer`` attribute that is a path that ends in ``.jinja2``: - -.. code-block:: xml - :linenos: - - <renderer - name=".jinja2" - factory="my.package.MyJinja2Renderer" - /> - -The ``factory`` attribute is a :term:`dotted Python name` that must -point to an implementation of a :term:`renderer factory`. - -The ``name`` attribute is the renderer name. - -Registering a Renderer Factory -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -See :ref:`adding_a_renderer` for more information for the definition of a -:term:`renderer factory`. Here's an example of the registration of a simple -:term:`renderer factory` via ZCML: - -.. code-block:: xml - :linenos: - - <renderer - name="amf" - factory="my.package.MyAMFRenderer" - /> - -Adding the above ZCML to your application will allow you to use the -``my.package.MyAMFRenderer`` renderer factory implementation in view -configurations by subseqently referring to it as ``amf`` in the ``renderer`` -attribute of a :term:`view configuration`: - -.. code-block:: xml - :linenos: - - <view - view="mypackage.views.my_view" - renderer="amf" - /> - -Here's an example of the registration of a more complicated renderer -factory, which expects to be passed a filesystem path: - -.. code-block:: xml - :linenos: - - <renderer - name=".jinja2" - factory="my.package.MyJinja2Renderer" - /> - -Adding the above ZCML to your application will allow you to use the -``my.package.MyJinja2Renderer`` renderer factory implementation in -view configurations by referring to any ``renderer`` which *ends in* -``.jinja`` in the ``renderer`` attribute of a :term:`view -configuration`: - -.. code-block:: xml - :linenos: - - <view - view="mypackage.views.my_view" - renderer="templates/mytemplate.jinja2" - /> - -When a :term:`view configuration` which has a ``name`` attribute that does -contain a dot, such as ``templates/mytemplate.jinja2`` above is encountered at -startup time, the value of the name attribute is split on its final dot. The -second element of the split is typically the filename extension. This -extension is used to look up a renderer factory for the configured view. Then -the value of ``renderer`` is passed to the factory to create a renderer for the -view. In this case, the view configuration will create an instance of a -``Jinja2Renderer`` for each view configuration which includes anything ending -with ``.jinja2`` as its ``renderer`` value. The ``name`` passed to the -``Jinja2Renderer`` constructor will be whatever the user passed as -``renderer=`` to the view configuration. - -See also :ref:`renderer_directive` and -:meth:`pyramid.config.Configurator.add_renderer`. - -Changing an Existing Renderer -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -You can associate more than one filename extension with the same -existing renderer implementation as necessary if you need to use a -different file extension for the same kinds of templates. For -example, to associate the ``.zpt`` extension with the Chameleon ZPT -renderer factory, use: - -.. code-block:: xml - :linenos: - - <renderer - name=".zpt" - factory="pyramid.chameleon_zpt.renderer_factory" - /> - -After you do this, :app:`Pyramid` will treat templates ending in -both the ``.pt`` and ``.zpt`` filename extensions as Chameleon ZPT -templates. - -To change the default mapping in which files with a ``.pt`` -extension are rendered via a Chameleon ZPT page template renderer, use -a variation on the following in your application's ZCML: - -.. code-block:: xml - :linenos: - - <renderer - name=".pt" - factory="my.package.pt_renderer" - /> - -After you do this, the :term:`renderer factory` in -``my.package.pt_renderer`` will be used to render templates which end -in ``.pt``, replacing the default Chameleon ZPT renderer. - -To ochange the default mapping in which files with a ``.txt`` -extension are rendered via a Chameleon text template renderer, use a -variation on the following in your application's ZCML: - -.. code-block:: xml - :linenos: - - <renderer - name=".txt" - factory="my.package.text_renderer" - /> - -After you do this, the :term:`renderer factory` in -``my.package.text_renderer`` will be used to render templates which -end in ``.txt``, replacing the default Chameleon text renderer. - -To associate a *default* renderer with *all* view configurations (even -ones which do not possess a ``renderer`` attribute), use a variation -on the following (ie. omit the ``name`` attribute to the renderer -tag): - -.. code-block:: xml - :linenos: - - <renderer - factory="pyramid.renderers.json_renderer_factory" - /> - -See also :ref:`renderer_directive` and -:meth:`pyramid.config.Configurator.add_renderer`. - -.. _zcml_adding_a_translation_directory: - -Adding a Translation Directory via ZCML ---------------------------------------- - -You can add a translation directory via ZCML by using the -:ref:`translationdir_directive` ZCML directive: - -.. code-block:: xml - :linenos: - - <translationdir dir="my.application:locale/"/> - -A message catalog in a translation directory added via -:ref:`translationdir_directive` will be merged into translations from -a message catalog added earlier if both translation directories -contain translations for the same locale and :term:`translation -domain`. - -See also :ref:`translationdir_directive` and -:ref:`adding_a_translation_directory`. - -.. _zcml_adding_a_locale_negotiator: - -Adding a Custom Locale Negotiator via ZCML ------------------------------------------- - -You can add a custom locale negotiator via ZCML by using the -:ref:`localenegotiator_directive` ZCML directive: - -.. code-block:: xml - :linenos: - - <localenegotiator - negotiator="my_application.my_module.my_locale_negotiator" - /> - -See also :ref:`custom_locale_negotiator` and -:ref:`localenegotiator_directive`. - -.. index:: - pair: subscriber; ZCML directive - -.. _zcml_event_listener: - -Configuring an Event Listener via ZCML --------------------------------------- - -You can configure an :term:`subscriber` by modifying your application's -``configure.zcml``. Here's an example of a bit of XML you can add to the -``configure.zcml`` file which registers the above ``mysubscriber`` function, -which we assume lives in a ``subscribers.py`` module within your application: - -.. code-block:: xml - :linenos: - - <subscriber - for="pyramid.events.NewRequest" - handler=".subscribers.mysubscriber" - /> - -See also :ref:`subscriber_directive` and :ref:`events_chapter`. - -.. index:: - single: not found view - -.. _notfound_zcml: - -Configuring a Not Found View via ZCML -------------------------------------- - -If your application uses :term:`ZCML`, you can replace the Not Found view by -placing something like the following ZCML in your ``configure.zcml`` file. - -.. code-block:: xml - :linenos: - - <view - view="helloworld.views.notfound_view" - context="pyramid.exceptions.NotFound" - /> - -Replace ``helloworld.views.notfound_view`` with the Python dotted name to the -notfound view you want to use. - -See :ref:`changing_the_notfound_view` for more information. - -.. index:: - single: forbidden view - -.. _forbidden_zcml: - -Configuring a Forbidden View via ZCML -------------------------------------- - -If your application uses :term:`ZCML`, you can replace the Forbidden view by -placing something like the following ZCML in your ``configure.zcml`` file. - -.. code-block:: xml - :linenos: - - <view - view="helloworld.views.notfound_view" - context="pyramid.exceptions.Forbidden" - /> - -Replace ``helloworld.views.forbidden_view`` with the Python dotted name to -the forbidden view you want to use. - -See :ref:`changing_the_forbidden_view` for more information. - -.. _changing_traverser_zcml: - -Configuring an Alternate Traverser via ZCML -------------------------------------------- - -Use an ``adapter`` stanza in your application's ``configure.zcml`` to -change the default traverser: - -.. code-block:: xml - :linenos: - - <adapter - factory="myapp.traversal.Traverser" - provides="pyramid.interfaces.ITraverser" - for="*" - /> - -Or to register a traverser for a specific resource type: - -.. code-block:: xml - :linenos: - - <adapter - factory="myapp.traversal.Traverser" - provides="pyramid.interfaces.ITraverser" - for="myapp.resources.MyRoot" - /> - -See :ref:`changing_the_traverser` for more information. - -.. index:: - single: url generator - -.. _changing_resource_url_zcml: - -Changing ``resource_url`` URL Generation via ZCML -------------------------------------------------- - -You can change how :func:`pyramid.url.resource_url` generates a URL for a -specific type of resource by adding an adapter statement to your -``configure.zcml``. - -.. code-block:: xml - :linenos: - - <adapter - factory="myapp.traversal.URLGenerator" - provides="pyramid.interfaces.IContextURL" - for="myapp.resources.MyRoot *" - /> - -See :ref:`changing_resource_url` for more information. - -.. _changing_request_factory_zcml: - -Changing the Request Factory via ZCML -------------------------------------- - -A ``MyRequest`` class can be registered via ZCML as a request factory through -the use of the ZCML ``utility`` directive. In the below, we assume it lives -in a package named ``mypackage.mymodule``. - -.. code-block:: xml - :linenos: - - <utility - component="mypackage.mymodule.MyRequest" - provides="pyramid.interfaces.IRequestFactory" - /> - -See :ref:`changing_request_factory` for more information. - -.. _adding_renderer_globals_zcml: - -Changing the Renderer Globals Factory via ZCML ----------------------------------------------- - -A renderer globals factory can be registered via ZCML as a through the use of -the ZCML ``utility`` directive. In the below, we assume a -``renderers_globals_factory`` function lives in a package named -``mypackage.mymodule``. - -.. code-block:: xml - :linenos: - - <utility - component="mypackage.mymodule.renderer_globals_factory" - provides="pyramid.interfaces.IRendererGlobalsFactory" - /> - -See :ref:`adding_renderer_globals` for more information. - diff --git a/pyramid/config.py b/pyramid/config.py index f3323ae5d..4e2c5f3b5 100644 --- a/pyramid/config.py +++ b/pyramid/config.py @@ -3,14 +3,12 @@ import os import re import sys import types -import threading import traceback import venusian from translationstring import ChameleonTranslate -from zope.configuration import xmlconfig from zope.configuration.config import GroupingContextDecorator from zope.configuration.config import ConfigurationMachine from zope.configuration.xmlconfig import registerCommonDirectives @@ -576,7 +574,7 @@ class Configurator(object): config = self.__class__.with_context(context) c(config) - def add_directive(self, name, directive): + def add_directive(self, name, directive, action_wrap=True): """ Add a directive method to the configurator. @@ -588,6 +586,12 @@ class Configurator(object): keyword arguments following. It should use config.action as necessary to perform actions. Directive methods can then be invoked like 'built-in' directives such as ``add_view``, ``add_route``, etc. + + The ``action_wrap`` argument should be ``True`` for directives which + perform ``config.action`` with potentially conflicting + discriminators. ``action_wrap`` will cause the directive to be + wrapped in a decorator which provides more accurate conflict + cause information. ``add_directive`` does not participate in conflict detection, and later calls to ``add_directive`` will override earlier calls. @@ -595,7 +599,7 @@ class Configurator(object): c = self.maybe_dotted(directive) if not hasattr(self.registry, '_directives'): self.registry._directives = {} - self.registry._directives[name] = c + self.registry._directives[name] = (c, action_wrap) def __getattr__(self, name): # allow directive extension names to work @@ -603,7 +607,9 @@ class Configurator(object): c = directives.get(name) if c is None: raise AttributeError(name) - c = action_method(c) + c, action_wrap = c + if action_wrap: + c = action_method(c) m = types.MethodType(c, self, self.__class__) return m @@ -919,47 +925,6 @@ class Configurator(object): self.manager.pop() return app - def load_zcml(self, spec='configure.zcml', lock=threading.Lock()): - """ Load configuration from a :term:`ZCML` file into the - current configuration state. The ``spec`` argument is an - absolute filename, a relative filename, or a :term:`asset - specification`, defaulting to ``configure.zcml`` (relative to - the package of the configurator's caller).""" - package_name, filename = self._split_spec(spec) - if package_name is None: # absolute filename - package = self.package - else: - __import__(package_name) - package = sys.modules[package_name] - - registry = self.registry - self.manager.push({'registry':registry, 'request':None}) - context = self._ctx - if context is None: - context = self._ctx = self._make_context(self.autocommit) - - # To avoid breaking people's expectations of how ZCML works, we - # cannot autocommit ZCML actions incrementally. If we commit actions - # incrementally, configuration outcome will be controlled purely by - # ZCML directive execution order, which isn't what anyone who uses - # ZCML expects. So we don't autocommit each ZCML directive action - # while parsing is happening, but we do make sure to pass - # execute=self.autocommit to xmlconfig.file below, which will cause - # the actions implied by the ZCML that was parsed to be committed - # right away once parsing is finished if autocommit is True. - context = GroupingContextDecorator(context) - context.autocommit = False - - lock.acquire() - try: - context.package = package - xmlconfig.file(filename, package, context=context, - execute=self.autocommit) - finally: - lock.release() - self.manager.pop() - return registry - @action_method def add_view(self, view=None, name="", for_=None, permission=None, request_type=None, route_name=None, request_method=None, diff --git a/pyramid/fixers/fix_bfg_imports.py b/pyramid/fixers/fix_bfg_imports.py index c29898a65..8fd32a797 100644 --- a/pyramid/fixers/fix_bfg_imports.py +++ b/pyramid/fixers/fix_bfg_imports.py @@ -177,7 +177,9 @@ MODULE_ALTERNATIVES = '|'.join(MODULE_ALTERNATIVES) BFG_NS_RE = r'xmlns\s*?=\s*?[\'\"]http://namespaces\.repoze\.org/bfg[\'\"]' BFG_IN_ATTR = r'(repoze\.bfg)(%s)' % MODULE_ALTERNATIVES +BFG_INCLUDE_IN_ATTR = r'repoze\.bfg\.includes' ATTR = re.compile(BFG_IN_ATTR, re.MULTILINE) +INCLUDE_ATTR = re.compile(BFG_INCLUDE_IN_ATTR, re.MULTILINE) NS = re.compile(BFG_NS_RE, re.MULTILINE) def replace(match): @@ -190,6 +192,7 @@ def fix_zcml(path): absfile = os.path.join(root, file) text = open(absfile, 'rb').read() newt = NS.sub('xmlns="http://pylonshq.com/pyramid"', text) + newt = INCLUDE_ATTR.sub('pyramid_zcml', newt) newt = ATTR.sub(replace, newt) if text != newt: newf = open(absfile, 'wb') diff --git a/pyramid/includes/__init__.py b/pyramid/includes/__init__.py deleted file mode 100644 index 9faa798e8..000000000 --- a/pyramid/includes/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# includes package: referred to by generated apps diff --git a/pyramid/includes/configure.zcml b/pyramid/includes/configure.zcml deleted file mode 100644 index 8ddd56406..000000000 --- a/pyramid/includes/configure.zcml +++ /dev/null @@ -1,5 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include file="meta.zcml" /> - -</configure> diff --git a/pyramid/includes/meta.zcml b/pyramid/includes/meta.zcml deleted file mode 100644 index e0a113ca3..000000000 --- a/pyramid/includes/meta.zcml +++ /dev/null @@ -1,123 +0,0 @@ -<configure - xmlns="http://namespaces.zope.org/zope" - xmlns:meta="http://namespaces.zope.org/meta"> - - <meta:directives namespace="http://pylonshq.com/pyramid"> - - <meta:directive - name="view" - schema="pyramid.zcml.IViewDirective" - handler="pyramid.zcml.view" - /> - - <meta:directive - name="scan" - schema="pyramid.zcml.IScanDirective" - handler="pyramid.zcml.scan" - /> - - <meta:directive - name="notfound" - schema="pyramid.zcml.ISystemViewDirective" - handler="pyramid.zcml.notfound" - /> - - <meta:directive - name="forbidden" - schema="pyramid.zcml.ISystemViewDirective" - handler="pyramid.zcml.forbidden" - /> - - <meta:directive - name="route" - schema="pyramid.zcml.IRouteDirective" - handler="pyramid.zcml.route" - /> - - <meta:directive - name="asset" - schema="pyramid.zcml.IAssetDirective" - handler="pyramid.zcml.asset" - /> - - <meta:directive - name="resource" - schema="pyramid.zcml.IAssetDirective" - handler="pyramid.zcml.asset" - /> - - <meta:directive - name="static" - schema="pyramid.zcml.IStaticDirective" - handler="pyramid.zcml.static" - /> - - <meta:directive - name="renderer" - schema="pyramid.zcml.IRendererDirective" - handler="pyramid.zcml.renderer" - /> - - <meta:directive - name="repozewho1authenticationpolicy" - schema="pyramid.zcml.IRepozeWho1AuthenticationPolicyDirective" - handler="pyramid.zcml.repozewho1authenticationpolicy" - /> - - <meta:directive - name="remoteuserauthenticationpolicy" - schema="pyramid.zcml.IRemoteUserAuthenticationPolicyDirective" - handler="pyramid.zcml.remoteuserauthenticationpolicy" - /> - - <meta:directive - name="authtktauthenticationpolicy" - schema="pyramid.zcml.IAuthTktAuthenticationPolicyDirective" - handler="pyramid.zcml.authtktauthenticationpolicy" - /> - - <meta:directive - name="aclauthorizationpolicy" - schema="pyramid.zcml.IACLAuthorizationPolicyDirective" - handler="pyramid.zcml.aclauthorizationpolicy" - /> - - <meta:directive - name="translationdir" - schema="pyramid.zcml.ITranslationDirDirective" - handler="pyramid.zcml.translationdir" - /> - - <meta:directive - name="localenegotiator" - schema="pyramid.zcml.ILocaleNegotiatorDirective" - handler="pyramid.zcml.localenegotiator" - /> - - <meta:directive - name="adapter" - schema="pyramid.zcml.IAdapterDirective" - handler="pyramid.zcml.adapter" - /> - - <meta:directive - name="subscriber" - schema="pyramid.zcml.ISubscriberDirective" - handler="pyramid.zcml.subscriber" - /> - - <meta:directive - name="utility" - schema="pyramid.zcml.IUtilityDirective" - handler="pyramid.zcml.utility" - /> - - <meta:directive - name="default_permission" - schema="pyramid.zcml.IDefaultPermissionDirective" - handler="pyramid.zcml.default_permission" - /> - - </meta:directives> - -</configure> diff --git a/pyramid/paster.py b/pyramid/paster.py index 488721ef0..80870b2ad 100644 --- a/pyramid/paster.py +++ b/pyramid/paster.py @@ -19,11 +19,6 @@ class StarterProjectTemplate(PyramidTemplate): summary = 'pyramid starter project' template_renderer = staticmethod(paste_script_template_renderer) -class StarterZCMLProjectTemplate(PyramidTemplate): - _template_dir = 'paster_templates/starter_zcml' - summary = 'pyramid starter project (ZCML)' - template_renderer = staticmethod(paste_script_template_renderer) - class ZODBProjectTemplate(PyramidTemplate): _template_dir = 'paster_templates/zodb' summary = 'pyramid ZODB starter project' diff --git a/pyramid/paster_templates/starter_zcml/+package+/__init__.py_tmpl b/pyramid/paster_templates/starter_zcml/+package+/__init__.py_tmpl deleted file mode 100644 index 25d45b949..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/__init__.py_tmpl +++ /dev/null @@ -1,11 +0,0 @@ -from pyramid.config import Configurator -from {{package}}.resources import Root - -def main(global_config, **settings): - """ This function returns a Pyramid WSGI application. - """ - zcml_file = settings.get('configure_zcml', 'configure.zcml') - config = Configurator(root_factory=Root, settings=settings) - config.load_zcml(zcml_file) - return config.make_wsgi_app() - diff --git a/pyramid/paster_templates/starter_zcml/+package+/configure.zcml b/pyramid/paster_templates/starter_zcml/+package+/configure.zcml deleted file mode 100644 index 41e40866b..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/configure.zcml +++ /dev/null @@ -1,17 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <!-- this must be included for the view declarations to work --> - <include package="pyramid.includes" /> - - <view - context=".resources.Root" - view=".views.my_view" - renderer="templates/mytemplate.pt" - /> - - <static - name="static" - path="static" - /> - -</configure> diff --git a/pyramid/paster_templates/starter_zcml/+package+/resources.py b/pyramid/paster_templates/starter_zcml/+package+/resources.py deleted file mode 100644 index 3d811895c..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/resources.py +++ /dev/null @@ -1,3 +0,0 @@ -class Root(object): - def __init__(self, request): - self.request = request diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/favicon.ico b/pyramid/paster_templates/starter_zcml/+package+/static/favicon.ico Binary files differdeleted file mode 100644 index 71f837c9e..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/favicon.ico +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/footerbg.png b/pyramid/paster_templates/starter_zcml/+package+/static/footerbg.png Binary files differdeleted file mode 100644 index 1fbc873da..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/footerbg.png +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/headerbg.png b/pyramid/paster_templates/starter_zcml/+package+/static/headerbg.png Binary files differdeleted file mode 100644 index 0596f2020..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/headerbg.png +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/ie6.css b/pyramid/paster_templates/starter_zcml/+package+/static/ie6.css deleted file mode 100644 index b7c8493d8..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/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/pyramid/paster_templates/starter_zcml/+package+/static/middlebg.png b/pyramid/paster_templates/starter_zcml/+package+/static/middlebg.png Binary files differdeleted file mode 100644 index 2369cfb7d..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/middlebg.png +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/pylons.css b/pyramid/paster_templates/starter_zcml/+package+/static/pylons.css deleted file mode 100644 index fd1914d8d..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/pylons.css +++ /dev/null @@ -1,65 +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:#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:"Neuton","Lucida Grande",Lucida,Verdana,sans-serif;font-weight:normal;color:#373839;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;vertical-align:middle;} -#header{background:#000000;top:0;font-size:14px;} -#footer{bottom:0;background:#000000 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:#000000;height:230px;background:#ffffff url(headerbg.png) repeat-x 0 top;position:relative;} -#top-small{color:#000000;height:60px;background:#ffffff url(headerbg.png) repeat-x 0 top;position:relative;} -#bottom{color:#222;background-color:#ffffff;} -.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 #ffffff;border-bottom:2px solid #b2b2b2;} -.app-welcome{margin-top:25px;} -.app-name{color:#000000;font-weight:bold;} -.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:bold;} -/*Opera Fix*/ -body:before{content:"";height:100%;float:left;width:0;margin-top:-32767px;} diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/pyramid-small.png b/pyramid/paster_templates/starter_zcml/+package+/static/pyramid-small.png Binary files differdeleted file mode 100644 index a5bc0ade7..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/pyramid-small.png +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/pyramid.png b/pyramid/paster_templates/starter_zcml/+package+/static/pyramid.png Binary files differdeleted file mode 100644 index 347e05549..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/pyramid.png +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/static/transparent.gif b/pyramid/paster_templates/starter_zcml/+package+/static/transparent.gif Binary files differdeleted file mode 100644 index 0341802e5..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/static/transparent.gif +++ /dev/null diff --git a/pyramid/paster_templates/starter_zcml/+package+/templates/mytemplate.pt_tmpl b/pyramid/paster_templates/starter_zcml/+package+/templates/mytemplate.pt_tmpl deleted file mode 100644 index e3fa39f28..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/templates/mytemplate.pt_tmpl +++ /dev/null @@ -1,75 +0,0 @@ -<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:tal="http://xml.zope.org/namespaces/tal"> -<head> - <title>The Pyramid Web Application Development Framework</title> - <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/> - <meta name="keywords" content="python web application" /> - <meta name="description" content="pyramid web application" /> - <link rel="shortcut icon" href="${request.static_url('{{package}}:static/favicon.ico')}" /> - <link rel="stylesheet" href="${request.static_url('{{package}}:static/pylons.css')}" type="text/css" media="screen" charset="utf-8" /> - <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Neuton|Nobile:regular,i,b,bi&subset=latin" type="text/css" media="screen" charset="utf-8" /> - <!--[if lte IE 6]> - <link rel="stylesheet" href="${request.static_url('{{package}}:static/ie6.css')}" type="text/css" media="screen" charset="utf-8" /> - <![endif]--> -</head> -<body> - <div id="wrap"> - <div id="top"> - <div class="top align-center"> - <div><img src="${request.static_url('{{package}}:static/pyramid.png')}" width="750" height="169" alt="pyramid"/></div> - </div> - </div> - <div id="middle"> - <div class="middle align-center"> - <p class="app-welcome"> - Welcome to <span class="app-name">${project}</span>, an application generated by<br/> - the Pyramid web application development framework. - </p> - </div> - </div> - <div id="bottom"> - <div class="bottom"> - <div id="left" class="align-right"> - <h2>Search documentation</h2> - <form method="get" action="http://docs.pylonsproject.org/projects/pyramid/dev/search.html"> - <input type="text" id="q" name="q" value="" /> - <input type="submit" id="x" value="Go" /> - </form> - </div> - <div id="right" class="align-left"> - <h2>Pyramid links</h2> - <ul class="links"> - <li> - <a href="http://pylonsproject.org">Pylons Website</a> - </li> - <li> - <a href="http://docs.pylonsproject.org/projects/pyramid/dev/#narrative-documentation">Narrative Documentation</a> - </li> - <li> - <a href="http://docs.pylonsproject.org/projects/pyramid/dev/#api-documentation">API Documentation</a> - </li> - <li> - <a href="http://docs.pylonsproject.org/projects/pyramid/dev/#tutorials">Tutorials</a> - </li> - <li> - <a href="http://docs.pylonsproject.org/projects/pyramid/dev/#change-history">Change History</a> - </li> - <li> - <a href="http://docs.pylonsproject.org/projects/pyramid/dev/#sample-applications">Sample Applications</a> - </li> - <li> - <a href="http://docs.pylonsproject.org/projects/pyramid/dev/#support-and-development">Support and Development</a> - </li> - <li> - <a href="irc://irc.freenode.net#pyramid">IRC Channel</a> - </li> - </ul> - </div> - </div> - </div> - </div> - <div id="footer"> - <div class="footer">© Copyright 2008-2011, Agendaless Consulting.</div> - </div> -</body> -</html>
\ No newline at end of file diff --git a/pyramid/paster_templates/starter_zcml/+package+/tests.py_tmpl b/pyramid/paster_templates/starter_zcml/+package+/tests.py_tmpl deleted file mode 100644 index 33f8c50b4..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/tests.py_tmpl +++ /dev/null @@ -1,18 +0,0 @@ -import unittest - -from pyramid import testing - -class ViewTests(unittest.TestCase): - def setUp(self): - self.config = testing.setUp() - - def tearDown(self): - testing.tearDown() - - def test_my_view(self): - from {{package}}.views import my_view - request = testing.DummyRequest() - info = my_view(request) - self.assertEqual(info['project'], '{{project}}') - - diff --git a/pyramid/paster_templates/starter_zcml/+package+/views.py_tmpl b/pyramid/paster_templates/starter_zcml/+package+/views.py_tmpl deleted file mode 100644 index 12ed8832d..000000000 --- a/pyramid/paster_templates/starter_zcml/+package+/views.py_tmpl +++ /dev/null @@ -1,2 +0,0 @@ -def my_view(request): - return {'project':'{{project}}'} diff --git a/pyramid/paster_templates/starter_zcml/CHANGES.txt_tmpl b/pyramid/paster_templates/starter_zcml/CHANGES.txt_tmpl deleted file mode 100644 index 35a34f332..000000000 --- a/pyramid/paster_templates/starter_zcml/CHANGES.txt_tmpl +++ /dev/null @@ -1,4 +0,0 @@ -0.0 ---- - -- Initial version diff --git a/pyramid/paster_templates/starter_zcml/README.txt_tmpl b/pyramid/paster_templates/starter_zcml/README.txt_tmpl deleted file mode 100644 index 0ddebfc3e..000000000 --- a/pyramid/paster_templates/starter_zcml/README.txt_tmpl +++ /dev/null @@ -1,4 +0,0 @@ -{{project}} README - - - diff --git a/pyramid/paster_templates/starter_zcml/development.ini_tmpl b/pyramid/paster_templates/starter_zcml/development.ini_tmpl deleted file mode 100644 index 574062b30..000000000 --- a/pyramid/paster_templates/starter_zcml/development.ini_tmpl +++ /dev/null @@ -1,44 +0,0 @@ -[app:{{project}}] -use = egg:{{project}} -reload_templates = true -debug_authorization = false -debug_notfound = false -debug_routematch = false -debug_templates = true -default_locale_name = en - -[pipeline:main] -pipeline = - egg:WebError#evalerror - {{project}} - -[server:main] -use = egg:Paste#http -host = 0.0.0.0 -port = 6543 - -# Begin logging configuration - -[loggers] -keys = root - -[handlers] -keys = console - -[formatters] -keys = generic - -[logger_root] -level = INFO -handlers = console - -[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/pyramid/paster_templates/starter_zcml/setup.cfg_tmpl b/pyramid/paster_templates/starter_zcml/setup.cfg_tmpl deleted file mode 100644 index 5bec29823..000000000 --- a/pyramid/paster_templates/starter_zcml/setup.cfg_tmpl +++ /dev/null @@ -1,27 +0,0 @@ -[nosetests] -match=^test -nocapture=1 -cover-package={{package}} -with-coverage=1 -cover-erase=1 - -[compile_catalog] -directory = {{package}}/locale -domain = {{project}} -statistics = true - -[extract_messages] -add_comments = TRANSLATORS: -output_file = {{package}}/locale/{{project}}.pot -width = 80 - -[init_catalog] -domain = {{project}} -input_file = {{package}}/locale/{{project}}.pot -output_dir = {{package}}/locale - -[update_catalog] -domain = {{project}} -input_file = {{package}}/locale/{{project}}.pot -output_dir = {{package}}/locale -previous = true diff --git a/pyramid/paster_templates/starter_zcml/setup.py_tmpl b/pyramid/paster_templates/starter_zcml/setup.py_tmpl deleted file mode 100644 index bd2642627..000000000 --- a/pyramid/paster_templates/starter_zcml/setup.py_tmpl +++ /dev/null @@ -1,37 +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', 'WebError'] - -setup(name='{{project}}', - version='0.0', - description='{{project}}', - 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="{{package}}", - entry_points = """\ - [paste.app_factory] - main = {{package}}:main - """, - paster_plugins=['pyramid'], - ) - diff --git a/pyramid/request.py b/pyramid/request.py index 475df744a..9ff94936c 100644 --- a/pyramid/request.py +++ b/pyramid/request.py @@ -232,8 +232,8 @@ class Request(WebobRequest): Generates a fully qualified URL for a static :term:`asset`. The asset must live within a location defined via the :meth:`pyramid.config.Configurator.add_static_view` - :term:`configuration declaration` or the ``<static>`` ZCML directive - (see :ref:`static_assets_section`). + :term:`configuration declaration` directive (see + :ref:`static_assets_section`). This is a convenience method. The result of calling :meth:`pyramid.request.Request.static_url` is the same as calling diff --git a/pyramid/router.py b/pyramid/router.py index b665eeee2..089b5b280 100644 --- a/pyramid/router.py +++ b/pyramid/router.py @@ -1,8 +1,6 @@ from zope.interface import implements from zope.interface import providedBy -from zope.deprecation import deprecated - from pyramid.interfaces import IDebugLogger from pyramid.interfaces import IExceptionViewClassifier from pyramid.interfaces import IRequest @@ -24,8 +22,6 @@ from pyramid.threadlocal import manager from pyramid.traversal import DefaultRootFactory from pyramid.traversal import ResourceTreeTraverser -from pyramid.config import Configurator # b/c - class Router(object): implements(IRouter) @@ -208,70 +204,3 @@ class Router(object): finally: manager.pop() - - - - - -# note that ``options`` is a b/w compat alias for ``settings`` and -# ``Configurator`` is a testing dep inj -def make_app(root_factory, package=None, filename='configure.zcml', - settings=None, options=None, Configurator=Configurator): - """ Return a Router object, representing a fully configured - :app:`Pyramid` WSGI application. - - .. warning:: Use of this function is deprecated as of - :app:`Pyramid` 1.0. You should instead use a - :class:`pyramid.config.Configurator` instance to - perform startup configuration as shown in - :ref:`configuration_narr`. - - ``root_factory`` must be a callable that accepts a :term:`request` - object and which returns a traversal root object. The traversal - root returned by the root factory is the *default* traversal root; - it can be overridden on a per-view basis. ``root_factory`` may be - ``None``, in which case a 'default default' traversal root is - used. - - ``package`` is a Python :term:`package` or module representing the - application's package. It is optional, defaulting to ``None``. - ``package`` may be ``None``. If ``package`` is ``None``, the - ``filename`` passed or the value in the ``options`` dictionary - named ``configure_zcml`` must be a) absolute pathname to a - :term:`ZCML` file that represents the application's configuration - *or* b) a :term:`asset specification` to a :term:`ZCML` file in - the form ``dotted.package.name:relative/file/path.zcml``. - - ``filename`` is the filesystem path to a ZCML file (optionally - relative to the package path) that should be parsed to create the - application registry. It defaults to ``configure.zcml``. It can - also be a ;term:`asset specification` in the form - ``dotted_package_name:relative/file/path.zcml``. Note that if any - value for ``configure_zcml`` is passed within the ``settings`` - dictionary, the value passed as ``filename`` will be ignored, - replaced with the ``configure_zcml`` value. - - ``settings``, if used, should be a dictionary containing runtime - settings (e.g. the key/value pairs in an app section of a - PasteDeploy file), with each key representing the option and the - key's value representing the specific option value, - e.g. ``{'reload_templates':True}``. Note that the keyword - parameter ``options`` is a backwards compatibility alias for the - ``settings`` keyword parameter. - """ - settings = settings or options or {} - zcml_file = settings.get('configure_zcml', filename) - config = Configurator(package=package, settings=settings, - root_factory=root_factory, autocommit=True) - config.hook_zca() - config.begin() - config.load_zcml(zcml_file) - config.end() - return config.make_wsgi_app() - - -deprecated( - 'make_app', - 'pyramid.router.make_app is deprecated as of Pyramid 1.0. Use ' - 'an instance of ``pyramid.config.Configurator`` to configure your ' - 'application instead.') diff --git a/pyramid/settings.py b/pyramid/settings.py index 3aaf63807..e33a8e086 100644 --- a/pyramid/settings.py +++ b/pyramid/settings.py @@ -46,8 +46,6 @@ class Settings(dict): config_reload_resources)) # reload_resources is an older alias for reload_assets eff_reload_assets = reload_assets or reload_resources - configure_zcml = self.get('configure_zcml', '') - eff_configure_zcml = eget('PYRAMID_CONFIGURE_ZCML', configure_zcml) locale_name = self.get('default_locale_name', 'en') eff_locale_name = eget('PYRAMID_DEFAULT_LOCALE_NAME', locale_name) @@ -59,7 +57,6 @@ class Settings(dict): 'reload_templates': eff_reload_all or eff_reload_templates, 'reload_resources':eff_reload_all or eff_reload_assets, 'reload_assets':eff_reload_all or eff_reload_assets, - 'configure_zcml':eff_configure_zcml, 'default_locale_name':eff_locale_name, } diff --git a/pyramid/static.py b/pyramid/static.py index 5e4faf6fe..86f596640 100644 --- a/pyramid/static.py +++ b/pyramid/static.py @@ -180,7 +180,6 @@ class static_view(object): .. note:: If the ``root_dir`` is relative to a :term:`package`, or is a :term:`asset specification` the :app:`Pyramid` - ``asset`` ZCML directive or :class:`pyramid.config.Configurator` method can be used to override assets within the named ``root_dir`` package-relative directory. However, if the ``root_dir`` is diff --git a/pyramid/tests/ccbugapp/__init__.py b/pyramid/tests/ccbugapp/__init__.py index 546616b2c..6c2eb6ecf 100644 --- a/pyramid/tests/ccbugapp/__init__.py +++ b/pyramid/tests/ccbugapp/__init__.py @@ -1 +1,7 @@ -# fixture application +def includeme(config): + config.add_route('rdf', + 'licenses/:license_code/:license_version/rdf', + '.views.rdf_view') + config.add_route('juri', + 'licenses/:license_code/:license_version/:jurisdiction', + '.views.juri_view') diff --git a/pyramid/tests/ccbugapp/configure.zcml b/pyramid/tests/ccbugapp/configure.zcml deleted file mode 100644 index f595f6b64..000000000 --- a/pyramid/tests/ccbugapp/configure.zcml +++ /dev/null @@ -1,15 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <route - view=".views.rdf_view" - path="licenses/:license_code/:license_version/rdf" - name="rdf" /> - - <route - view=".views.juri_view" - path="licenses/:license_code/:license_version/:jurisdiction" - name="juri" /> - -</configure> diff --git a/pyramid/tests/defpermbugapp/__init__.py b/pyramid/tests/defpermbugapp/__init__.py index 82a189b9e..957bd08f6 100644 --- a/pyramid/tests/defpermbugapp/__init__.py +++ b/pyramid/tests/defpermbugapp/__init__.py @@ -12,3 +12,14 @@ def y_view(request): # pragma: no cover @view_config(name='z', permission='__no_permission_required__') def z_view(request): return Response('this is public') + +def includeme(config): + from pyramid.authorization import ACLAuthorizationPolicy + from pyramid.authentication import AuthTktAuthenticationPolicy + authn_policy = AuthTktAuthenticationPolicy('seekt1t') + authz_policy = ACLAuthorizationPolicy() + config.scan('pyramid.tests.defpermbugapp') + config._set_authentication_policy(authn_policy) + config._set_authorization_policy(authz_policy) + config.set_default_permission('private') + diff --git a/pyramid/tests/defpermbugapp/configure.zcml b/pyramid/tests/defpermbugapp/configure.zcml deleted file mode 100644 index f9680bb04..000000000 --- a/pyramid/tests/defpermbugapp/configure.zcml +++ /dev/null @@ -1,14 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <scan package="pyramid.tests.defpermbugapp"/> - - <authtktauthenticationpolicy - secret="seekt1t"/> - - <aclauthorizationpolicy/> - - <default_permission name="private" /> - -</configure> diff --git a/pyramid/tests/exceptionviewapp/__init__.py b/pyramid/tests/exceptionviewapp/__init__.py index ef5fe8b12..cf69227cd 100644 --- a/pyramid/tests/exceptionviewapp/__init__.py +++ b/pyramid/tests/exceptionviewapp/__init__.py @@ -1 +1,21 @@ -# a package +def includeme(config): + config.add_view('.views.maybe') + config.add_view('.views.no', context='.models.NotAnException') + config.add_view('.views.yes', context=".models.AnException") + config.add_view('.views.raise_exception', name='raise_exception') + config.add_route('route_raise_exception', 'route_raise_exception', + view='.views.raise_exception') + config.add_route('route_raise_exception2', + 'route_raise_exception2', + view='.views.raise_exception', + factory='.models.route_factory') + config.add_route('route_raise_exception3', + 'route_raise_exception3', + view='.views.raise_exception', + factory='.models.route_factory2') + config.add_view('.views.whoa', context='.models.AnException', + route_name='route_raise_exception3') + config.add_route('route_raise_exception4', 'route_raise_exception4', + view='.views.raise_exception') + config.add_view('.views.whoa', context='.models.AnException', + route_name='route_raise_exception4') diff --git a/pyramid/tests/exceptionviewapp/configure.zcml b/pyramid/tests/exceptionviewapp/configure.zcml deleted file mode 100644 index ec2b23eda..000000000 --- a/pyramid/tests/exceptionviewapp/configure.zcml +++ /dev/null @@ -1,44 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view view=".views.maybe"/> - - <view context=".models.NotAnException" - view=".views.no"/> - - <view context=".models.AnException" - view=".views.yes"/> - - <view name="raise_exception" - view=".views.raise_exception"/> - - <route name="route_raise_exception" - path="route_raise_exception" - view=".views.raise_exception"/> - - <route name="route_raise_exception2" - path="route_raise_exception2" - view=".views.raise_exception" - factory=".models.route_factory"/> - - <route name="route_raise_exception3" - path="route_raise_exception3" - view=".views.raise_exception" - factory=".models.route_factory2"/> - - <view context=".models.AnException" - route_name="route_raise_exception3" - view=".views.whoa"/> - - <route name="route_raise_exception4" - path="route_raise_exception4" - view=".views.raise_exception"/> - - <view context=".models.AnException" - route_name="route_raise_exception4" - view=".views.whoa"/> - -</configure> - - diff --git a/pyramid/tests/fixtureapp/__init__.py b/pyramid/tests/fixtureapp/__init__.py index 546616b2c..c74747bfd 100644 --- a/pyramid/tests/fixtureapp/__init__.py +++ b/pyramid/tests/fixtureapp/__init__.py @@ -1 +1,12 @@ -# fixture application +def includeme(config): + config.add_view('.views.fixture_view') + config.add_view('.views.exception_view', context=RuntimeError) + config.add_view('.views.protected_view', name='protected.html') + config.add_view('.views.erroneous_view', name='error.html') + config.add_view('.views.fixture_view', name='dummyskin.html', + request_type='.views.IDummy') + from models import fixture, IFixture + config.registry.registerUtility(fixture, IFixture) + config.add_view('.views.fixture_view', name='another.html') + + diff --git a/pyramid/tests/fixtureapp/another.zcml b/pyramid/tests/fixtureapp/another.zcml deleted file mode 100644 index 07dda64d3..000000000 --- a/pyramid/tests/fixtureapp/another.zcml +++ /dev/null @@ -1,10 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view=".views.fixture_view" - name="another.html" - /> - -</configure> diff --git a/pyramid/tests/fixtureapp/configure.zcml b/pyramid/tests/fixtureapp/configure.zcml deleted file mode 100644 index 859940663..000000000 --- a/pyramid/tests/fixtureapp/configure.zcml +++ /dev/null @@ -1,37 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view=".views.fixture_view" - /> - - <view - view=".views.exception_view" - for="RuntimeError" - /> - - <view - view=".views.protected_view" - name="protected.html" - /> - - <view - view=".views.erroneous_view" - name="error.html" - /> - - <view - view=".views.fixture_view" - name="dummyskin.html" - request_type=".views.IDummy" - /> - - <utility - component=".models.fixture" - provides=".models.IFixture" - /> - - <include file="another.zcml"/> - -</configure> diff --git a/pyramid/tests/fixtureapp/subpackage/yetanother.zcml b/pyramid/tests/fixtureapp/subpackage/yetanother.zcml deleted file mode 100644 index 092e5e285..000000000 --- a/pyramid/tests/fixtureapp/subpackage/yetanother.zcml +++ /dev/null @@ -1,8 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <include package="pyramid.tests.fixtureapp" file="another.zcml"/> - -</configure> - diff --git a/pyramid/tests/grokkedapp/configure.zcml b/pyramid/tests/grokkedapp/configure.zcml deleted file mode 100644 index 169c42128..000000000 --- a/pyramid/tests/grokkedapp/configure.zcml +++ /dev/null @@ -1,6 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - <scan package="."/> - -</configure> diff --git a/pyramid/tests/hybridapp/__init__.py b/pyramid/tests/hybridapp/__init__.py index 5bb534f79..5b51e3d1e 100644 --- a/pyramid/tests/hybridapp/__init__.py +++ b/pyramid/tests/hybridapp/__init__.py @@ -1 +1,38 @@ -# package +def includeme(config): + # <!-- we want this view to "win" --> + config.add_route('route', 'abc', view='.views.route_view') + # <!-- .. even though this one has a more specific context --> + config.add_view('.views.global_view', + context='pyramid.traversal.DefaultRootFactory') + config.add_view('.views.global2_view', + context='pyramid.traversal.DefaultRootFactory', + name='global2') + config.add_route('route2', 'def') + # <!-- we want this view to win for route2 even though global view with + # context is more specific --> + config.add_view('.views.route2_view', route_name='route2') + + # <!-- the global view should be found for this route --> + config.add_route('route3', 'ghi', use_global_views=True) + # <!-- the global view should not be found for this route --> + config.add_route('route4', 'jkl') + # <!-- the global view should not be found for this route (/global2) --> + config.add_route('route5', 'mno/*traverse') + # <!-- the global view should be found for this route (/global2) --> + config.add_route('route6', 'pqr/*traverse', use_global_views=True) + config.add_route('route7', 'error') + config.add_view('.views.erroneous_view', route_name='route7') + config.add_route('route8', 'error2') + config.add_view('.views.erroneous_view', route_name='route8') + # <!-- we want this view to "win" for route7 as exception view --> + config.add_view('.views.exception_view', context=RuntimeError) + # <!-- we want this view to "win" for route8 as exception view--> + config.add_view('.views.exception2_view', context=RuntimeError, + route_name='route8') + config.add_route('route9', 'error_sub') + config.add_view('.views.erroneous_sub_view', route_name='route9') + # <!-- we want this view to "win" for route9 as exception view... --> + config.add_view('.views.exception2_view', context='.views.SuperException', + route_name='route9') + # <!-- ...even if we have more context-specialized view for exception --> + config.add_view('.views.exception_view', context='.views.SubException') diff --git a/pyramid/tests/hybridapp/configure.zcml b/pyramid/tests/hybridapp/configure.zcml deleted file mode 100644 index 5d85ec9d5..000000000 --- a/pyramid/tests/hybridapp/configure.zcml +++ /dev/null @@ -1,117 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <!-- we want this view to "win" --> - <route - view=".views.route_view" - path="abc" - name="route" /> - - <!-- .. even though this one has a more specific context --> - <view - view=".views.global_view" - context="pyramid.traversal.DefaultRootFactory" - /> - - <view - name="global2" - view=".views.global2_view" - context="pyramid.traversal.DefaultRootFactory" - /> - - <route - path="def" - name="route2" - /> - - <!-- we want this view to win for route2 even though global view with - context is more specific --> - <view - route_name="route2" - view=".views.route2_view" - /> - - <!-- the global view should be found for this route --> - <route - path="ghi" - name="route3" - use_global_views="True" - /> - - <!-- the global view should not be found for this route --> - <route - path="jkl" - name="route4" - /> - - <!-- the global view should not be found for this route (/global2) --> - <route - path="mno/*traverse" - name="route5" - /> - - <!-- the global view should be found for this route (/global2) --> - <route - path="pqr/*traverse" - name="route6" - use_global_views="True" - /> - - <route - path="error" - name="route7" - /> - - <view - route_name="route7" - view=".views.erroneous_view" - /> - - <route - path="error2" - name="route8" - /> - - <view - route_name="route8" - view=".views.erroneous_view" - /> - - <!-- we want this view to "win" for route7 as exception view --> - <view - view=".views.exception_view" - for="RuntimeError" - /> - - <!-- we want this view to "win" for route8 as exception view--> - <view - route_name="route8" - view=".views.exception2_view" - for="RuntimeError" - /> - - <route - path="error_sub" - name="route9" - /> - - <view - route_name="route9" - view=".views.erroneous_sub_view" - /> - - <!-- we want this view to "win" for route9 as exception view... --> - <view - route_name="route9" - view=".views.exception2_view" - for=".views.SuperException" - /> - - <!-- ...even if we have more context-specialized view for raised exception --> - <view - view=".views.exception_view" - for=".views.SubException" - /> - -</configure> diff --git a/pyramid/tests/permbugapp/__init__.py b/pyramid/tests/permbugapp/__init__.py index a64084a36..fe90c716d 100644 --- a/pyramid/tests/permbugapp/__init__.py +++ b/pyramid/tests/permbugapp/__init__.py @@ -10,3 +10,13 @@ def test(context, request): msg = 'Allow ./x? %s' % repr(view_execution_permitted( context, request, 'x')) return Response(escape(msg)) + +def includeme(config): + from pyramid.authentication import AuthTktAuthenticationPolicy + from pyramid.authorization import ACLAuthorizationPolicy + authn_policy = AuthTktAuthenticationPolicy('seekt1t') + authz_policy = ACLAuthorizationPolicy() + config._set_authentication_policy(authn_policy) + config._set_authorization_policy(authz_policy) + config.add_view(test, name='test') + config.add_view(x_view, name='x', permission='private') diff --git a/pyramid/tests/permbugapp/configure.zcml b/pyramid/tests/permbugapp/configure.zcml deleted file mode 100644 index 13159e394..000000000 --- a/pyramid/tests/permbugapp/configure.zcml +++ /dev/null @@ -1,21 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <view - view=".test" - name="test" - /> - - <view - view=".x_view" - name="x" - permission="private" - /> - - <authtktauthenticationpolicy - secret="seekt1t"/> - - <aclauthorizationpolicy/> - -</configure> diff --git a/pyramid/tests/restbugapp/__init__.py b/pyramid/tests/restbugapp/__init__.py index 5bb534f79..461fcce92 100644 --- a/pyramid/tests/restbugapp/__init__.py +++ b/pyramid/tests/restbugapp/__init__.py @@ -1 +1,14 @@ -# package +def includeme(config): + config.add_route('gameactions_pet_get_pets', '/pet', + view='.views.PetRESTView', + view_attr='GET', + request_method='GET', + permission='view', + renderer='json') + config.add_route('gameactions_pet_care_for_pet', '/pet', + view='.views.PetRESTView', + view_attr='POST', + request_method='POST', + permission='view', + renderer='json') + diff --git a/pyramid/tests/restbugapp/configure.zcml b/pyramid/tests/restbugapp/configure.zcml deleted file mode 100644 index ce0159d43..000000000 --- a/pyramid/tests/restbugapp/configure.zcml +++ /dev/null @@ -1,25 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes"/> - - <route - path="/pet" - name="gameactions_pet_get_pets" - view=".views.PetRESTView" - view_attr="GET" - request_method="GET" - permission="view" - renderer="json" - /> - - <route - path="/pet" - name="gameactions_pet_care_for_pet" - view=".views.PetRESTView" - view_attr="POST" - request_method="POST" - permission="view" - renderer="json" - /> - -</configure> diff --git a/pyramid/tests/routesapp/__init__.py b/pyramid/tests/routesapp/__init__.py deleted file mode 100644 index 546616b2c..000000000 --- a/pyramid/tests/routesapp/__init__.py +++ /dev/null @@ -1 +0,0 @@ -# fixture application diff --git a/pyramid/tests/routesapp/configure.zcml b/pyramid/tests/routesapp/configure.zcml deleted file mode 100644 index 99c05f4ec..000000000 --- a/pyramid/tests/routesapp/configure.zcml +++ /dev/null @@ -1,12 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - - <route - path=":id" - name="default" - view=".views.fixture_view" - permission="repoze.view" - /> - -</configure> diff --git a/pyramid/tests/routesapp/models.py b/pyramid/tests/routesapp/models.py deleted file mode 100644 index a57b06308..000000000 --- a/pyramid/tests/routesapp/models.py +++ /dev/null @@ -1,5 +0,0 @@ -from zope.interface import Interface - -class IFixture(Interface): - pass - diff --git a/pyramid/tests/routesapp/templates/fixture.pt b/pyramid/tests/routesapp/templates/fixture.pt deleted file mode 100644 index 06dd4e2b1..000000000 --- a/pyramid/tests/routesapp/templates/fixture.pt +++ /dev/null @@ -1,6 +0,0 @@ -<html xmlns="http://www.w3.org/1999/xhtml" - xmlns:tal="http://xml.zope.org/namespaces/tal"> -<head></head> -<body> -</body> -</html> diff --git a/pyramid/tests/routesapp/views.py b/pyramid/tests/routesapp/views.py deleted file mode 100644 index f805b88c9..000000000 --- a/pyramid/tests/routesapp/views.py +++ /dev/null @@ -1,8 +0,0 @@ -from zope.interface import Interface - -def fixture_view(context, request): - """ """ - -class IDummy(Interface): - pass - diff --git a/pyramid/tests/test_config.py b/pyramid/tests/test_config.py index 1073e53cc..7135501b9 100644 --- a/pyramid/tests/test_config.py +++ b/pyramid/tests/test_config.py @@ -576,54 +576,6 @@ class ConfiguratorTests(unittest.TestCase): self.assertEqual(len(subscriber), 1) self.failUnless(IApplicationCreated.providedBy(subscriber[0])) - def test_load_zcml_default(self): - import pyramid.tests.fixtureapp - config = self._makeOne(package=pyramid.tests.fixtureapp, - autocommit=True) - registry = config.load_zcml() - from pyramid.tests.fixtureapp.models import IFixture - self.failUnless(registry.queryUtility(IFixture)) # only in c.zcml - - def test_load_zcml_routesapp(self): - from pyramid.interfaces import IRoutesMapper - config = self._makeOne(autocommit=True) - config.load_zcml('pyramid.tests.routesapp:configure.zcml') - self.failUnless(config.registry.getUtility(IRoutesMapper)) - - def test_load_zcml_fixtureapp(self): - from pyramid.tests.fixtureapp.models import IFixture - config = self._makeOne(autocommit=True) - config.load_zcml('pyramid.tests.fixtureapp:configure.zcml') - self.failUnless(config.registry.queryUtility(IFixture)) # only in c.zcml - - def test_load_zcml_as_relative_filename(self): - import pyramid.tests.fixtureapp - config = self._makeOne(package=pyramid.tests.fixtureapp, - autocommit=True) - registry = config.load_zcml('configure.zcml') - from pyramid.tests.fixtureapp.models import IFixture - self.failUnless(registry.queryUtility(IFixture)) # only in c.zcml - - def test_load_zcml_as_absolute_filename(self): - import os - import pyramid.tests.fixtureapp - config = self._makeOne(package=pyramid.tests.fixtureapp, - autocommit=True) - dn = os.path.dirname(pyramid.tests.fixtureapp.__file__) - c_z = os.path.join(dn, 'configure.zcml') - registry = config.load_zcml(c_z) - from pyramid.tests.fixtureapp.models import IFixture - self.failUnless(registry.queryUtility(IFixture)) # only in c.zcml - - def test_load_zcml_lock_and_unlock(self): - config = self._makeOne(autocommit=True) - dummylock = DummyLock() - config.load_zcml( - 'pyramid.tests.fixtureapp:configure.zcml', - lock=dummylock) - self.assertEqual(dummylock.acquired, True) - self.assertEqual(dummylock.released, True) - def test_include_with_dotted_name(self): from pyramid import tests config = self._makeOne() @@ -2956,7 +2908,7 @@ class ConfiguratorTests(unittest.TestCase): def test___getattr__matches(self): config = self._makeOne() def foo(config): pass - directives = {'foo':foo} + directives = {'foo':(foo, True)} config.registry._directives = directives foo_meth = config.foo self.failUnless(foo_meth.im_func.__docobj__ is foo) @@ -4579,13 +4531,6 @@ class DummyRequest: class DummyContext: pass -class DummyLock: - def acquire(self): - self.acquired = True - - def release(self): - self.released = True - class DummyPackage: def __init__(self, name): self.__name__ = name diff --git a/pyramid/tests/test_integration.py b/pyramid/tests/test_integration.py index 971c4832e..5b1e137d7 100644 --- a/pyramid/tests/test_integration.py +++ b/pyramid/tests/test_integration.py @@ -66,11 +66,13 @@ class TestStaticApp(unittest.TestCase): class IntegrationBase(unittest.TestCase): root_factory = None + package = None def setUp(self): from pyramid.config import Configurator - config = Configurator(root_factory=self.root_factory) + config = Configurator(root_factory=self.root_factory, + package=self.package) config.begin() - config.load_zcml(self.config) + config.include(self.package) config.commit() app = config.make_wsgi_app() from webtest import TestApp @@ -81,7 +83,7 @@ class IntegrationBase(unittest.TestCase): self.config.end() class TestFixtureApp(IntegrationBase): - config = 'pyramid.tests.fixtureapp:configure.zcml' + package = 'pyramid.tests.fixtureapp' def test_another(self): res = self.testapp.get('/another.html', status=200) self.assertEqual(res.body, 'fixture') @@ -103,7 +105,7 @@ class TestFixtureApp(IntegrationBase): class TestCCBug(IntegrationBase): # "unordered" as reported in IRC by author of # http://labs.creativecommons.org/2010/01/13/cc-engine-and-web-non-frameworks/ - config = 'pyramid.tests.ccbugapp:configure.zcml' + package = 'pyramid.tests.ccbugapp' def test_rdf(self): res = self.testapp.get('/licenses/1/v1/rdf', status=200) self.assertEqual(res.body, 'rdf') @@ -116,7 +118,7 @@ class TestHybridApp(IntegrationBase): # make sure views registered for a route "win" over views registered # without one, even though the context of the non-route view may # be more specific than the route view. - config = 'pyramid.tests.hybridapp:configure.zcml' + package = 'pyramid.tests.hybridapp' def test_root(self): res = self.testapp.get('/', status=200) self.assertEqual(res.body, 'global') @@ -157,13 +159,13 @@ class TestHybridApp(IntegrationBase): class TestRestBugApp(IntegrationBase): # test bug reported by delijati 2010/2/3 (http://pastebin.com/d4cc15515) - config = 'pyramid.tests.restbugapp:configure.zcml' + package = 'pyramid.tests.restbugapp' def test_it(self): res = self.testapp.get('/pet', status=200) self.assertEqual(res.body, 'gotten') class TestViewDecoratorApp(IntegrationBase): - config = 'pyramid.tests.viewdecoratorapp:configure.zcml' + package = 'pyramid.tests.viewdecoratorapp' def _configure_mako(self): tmpldir = os.path.join(os.path.dirname(__file__), 'viewdecoratorapp', 'views') @@ -183,7 +185,7 @@ class TestViewDecoratorApp(IntegrationBase): class TestViewPermissionBug(IntegrationBase): # view_execution_permitted bug as reported by Shane at http://lists.repoze.org/pipermail/repoze-dev/2010-October/003603.html - config = 'pyramid.tests.permbugapp:configure.zcml' + package = 'pyramid.tests.permbugapp' def test_test(self): res = self.testapp.get('/test', status=200) self.failUnless('ACLDenied' in res.body) @@ -193,7 +195,7 @@ class TestViewPermissionBug(IntegrationBase): class TestDefaultViewPermissionBug(IntegrationBase): # default_view_permission bug as reported by Wiggy at http://lists.repoze.org/pipermail/repoze-dev/2010-October/003602.html - config = 'pyramid.tests.defpermbugapp:configure.zcml' + package = 'pyramid.tests.defpermbugapp' def test_x(self): res = self.testapp.get('/x', status=401) self.failUnless('failed permission check' in res.body) @@ -211,7 +213,7 @@ excroot = {'anexception':AnException(), 'notanexception':NotAnException()} class TestExceptionViewsApp(IntegrationBase): - config = 'pyramid.tests.exceptionviewapp:configure.zcml' + package = 'pyramid.tests.exceptionviewapp' root_factory = lambda *arg: excroot def test_root(self): res = self.testapp.get('/', status=200) diff --git a/pyramid/tests/test_router.py b/pyramid/tests/test_router.py index 65a1b82a4..95fbfa9b6 100644 --- a/pyramid/tests/test_router.py +++ b/pyramid/tests/test_router.py @@ -998,79 +998,6 @@ class TestRouter(unittest.TestCase): start_response = DummyStartResponse() self.assertRaises(RuntimeError, router, environ, start_response) -class TestMakeApp(unittest.TestCase): - def setUp(self): - from zope.deprecation import __show__ - __show__.off() - testing.setUp() - - def tearDown(self): - from zope.deprecation import __show__ - __show__.on() - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.router import make_app - return make_app(*arg, **kw) - - def test_it(self): - settings = {'a':1} - rootfactory = object() - app = self._callFUT(rootfactory, settings=settings, - Configurator=DummyConfigurator) - self.assertEqual(app.root_factory, rootfactory) - self.assertEqual(app.settings, settings) - self.assertEqual(app.zcml_file, 'configure.zcml') - self.assertEqual(app.zca_hooked, True) - - def test_it_options_means_settings(self): - settings = {'a':1} - rootfactory = object() - app = self._callFUT(rootfactory, options=settings, - Configurator=DummyConfigurator) - self.assertEqual(app.root_factory, rootfactory) - self.assertEqual(app.settings, settings) - self.assertEqual(app.zcml_file, 'configure.zcml') - - def test_it_with_package(self): - package = object() - rootfactory = object() - app = self._callFUT(rootfactory, package=package, - Configurator=DummyConfigurator) - self.assertEqual(app.package, package) - - def test_it_with_custom_configure_zcml(self): - rootfactory = object() - settings = {'configure_zcml':'2.zcml'} - app = self._callFUT(rootfactory, filename='1.zcml', settings=settings, - Configurator=DummyConfigurator) - self.assertEqual(app.zcml_file, '2.zcml') - -class DummyConfigurator(object): - def __init__(self, registry=None, package=None, root_factory=None, - settings=None, autocommit=True): - self.root_factory = root_factory - self.package = package - self.settings = settings - self.autocommit = autocommit - - def begin(self, request=None): - self.begun = True - self.request = request - - def end(self): - self.ended = True - - def load_zcml(self, filename): - self.zcml_file = filename - - def make_wsgi_app(self): - return self - - def hook_zca(self): - self.zca_hooked = True - - class DummyContext: pass diff --git a/pyramid/tests/test_settings.py b/pyramid/tests/test_settings.py index 9eb1cd30b..5e28000a6 100644 --- a/pyramid/tests/test_settings.py +++ b/pyramid/tests/test_settings.py @@ -27,7 +27,6 @@ class TestSettings(unittest.TestCase): self.assertEqual(settings['debug_routematch'], False) self.assertEqual(settings['reload_templates'], False) self.assertEqual(settings['reload_resources'], False) - self.assertEqual(settings['configure_zcml'], '') def test_reload_templates(self): settings = self._makeOne({}) @@ -209,17 +208,6 @@ class TestSettings(unittest.TestCase): self.assertEqual(result['debug_authorization'], True) self.assertEqual(result['debug_templates'], True) - def test_configure_zcml(self): - result = self._makeOne({}) - self.assertEqual(result['configure_zcml'], '') - result = self._makeOne({'configure_zcml':'abc'}) - self.assertEqual(result['configure_zcml'], 'abc') - result = self._makeOne({}, {'PYRAMID_CONFIGURE_ZCML':'abc'}) - self.assertEqual(result['configure_zcml'], 'abc') - result = self._makeOne({'configure_zcml':'def'}, - {'PYRAMID_CONFIGURE_ZCML':'abc'}) - self.assertEqual(result['configure_zcml'], 'abc') - def test_default_locale_name(self): result = self._makeOne({}) self.assertEqual(result['default_locale_name'], 'en') diff --git a/pyramid/tests/test_zcml.py b/pyramid/tests/test_zcml.py deleted file mode 100644 index af0ac9742..000000000 --- a/pyramid/tests/test_zcml.py +++ /dev/null @@ -1,1298 +0,0 @@ -import logging - -logging.basicConfig() - -import unittest - -from pyramid import testing - -from zope.interface import Interface -from zope.interface import implements - -class TestViewDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import view - return view(*arg, **kw) - - def test_with_dotted_renderer(self): - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRendererFactory - from pyramid.interfaces import IRequest - reg = self.config.registry - context = self.config._ctx - def factory(path): - def foo(*arg): - return 'OK' - return foo - reg.registerUtility(factory, IRendererFactory, name='.pt') - view = lambda *arg: None - self._callFUT(context, 'repoze.view', IDummy, view=view, - renderer='foo/template.pt') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - discrim = ('view', IDummy, '', None, IView, None, None, None, None, - None, False, None, None, None) - self.assertEqual(actions[0]['discriminator'], discrim) - register = actions[0]['callable'] - register() - regview = reg.adapters.lookup( - (IViewClassifier, IRequest, IDummy), IView, name='') - self.assertEqual(regview(None, None).body, 'OK') - - def test_with_custom_predicates(self): - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRequest - reg = self.config.registry - context = self.config._ctx - view = lambda *arg: 'OK' - def pred1(context, request): - return True - def pred2(context, request): - return True - preds = (pred1, pred2) - self._callFUT(context, 'repoze.view', IDummy, view=view, - custom_predicates=preds) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - discrim = ('view', IDummy, '', None, IView, None, None, None, None, - None, False, None, None, None) - discrim = discrim + tuple(sorted(preds)) - self.assertEqual(actions[0]['discriminator'], discrim) - register = actions[0]['callable'] - register() - regview = reg.adapters.lookup( - (IViewClassifier, IRequest, IDummy), IView, name='') - self.assertEqual(regview(None, None), 'OK') - - def test_context_trumps_for(self): - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRequest - reg = self.config.registry - context = self.config._ctx - view = lambda *arg: 'OK' - class Foo: - pass - self._callFUT(context, 'repoze.view', for_=Foo, view=view, - context=IDummy) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - discrim = ('view', IDummy, '', None, IView, None, None, None, None, - None, False, None, None, None) - self.assertEqual(actions[0]['discriminator'], discrim) - register = actions[0]['callable'] - register() - regview = reg.adapters.lookup( - (IViewClassifier, IRequest, IDummy), IView, name='') - self.assertEqual(regview(None, None), 'OK') - - def test_with_for(self): - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRequest - reg = self.config.registry - context = self.config._ctx - view = lambda *arg: 'OK' - class Foo: - pass - self._callFUT(context, 'repoze.view', for_=IDummy, view=view) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - discrim = ('view', IDummy, '', None, IView, None, None, None, None, - None, False, None, None, None) - self.assertEqual(actions[0]['discriminator'], discrim) - register = actions[0]['callable'] - register() - regview = reg.adapters.lookup( - (IViewClassifier, IRequest, IDummy), IView, name='') - self.assertEqual(regview(None, None), 'OK') - -class TestNotFoundDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, view, **kw): - from pyramid.zcml import notfound - return notfound(context, view, **kw) - - def test_it(self): - from zope.interface import implementedBy - from pyramid.interfaces import IRequest - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.exceptions import NotFound - - reg = self.config.registry - context = self.config._ctx - def view(request): - return 'OK' - self._callFUT(context, view) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - - discrim = ('view', NotFound, '', None, IView, None, None, None, None, - None, False, None, None, None) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], discrim) - register = regadapt['callable'] - register() - derived_view = reg.adapters.lookup( - (IViewClassifier, IRequest, implementedBy(NotFound)), - IView, default=None) - - self.assertNotEqual(derived_view, None) - self.assertEqual(derived_view(None, None), 'OK') - self.assertEqual(derived_view.__name__, 'bwcompat_view') - - def test_it_with_dotted_renderer(self): - from zope.interface import implementedBy - from pyramid.interfaces import IRequest - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.exceptions import NotFound - from pyramid.config import Configurator - reg = self.config.registry - config = Configurator(reg) - def dummy_renderer_factory(*arg, **kw): - return lambda *arg, **kw: 'OK' - config.add_renderer('.pt', dummy_renderer_factory) - config.commit() - def view(request): - return {} - context = self.config._ctx - self._callFUT(context, view, renderer='fake.pt') - actions = extract_actions(context.actions) - regadapt = actions[0] - register = regadapt['callable'] - register() - derived_view = reg.adapters.lookup( - (IViewClassifier, IRequest, implementedBy(NotFound)), - IView, default=None) - self.assertNotEqual(derived_view, None) - self.assertEqual(derived_view(None, None).body, 'OK') - self.assertEqual(derived_view.__name__, 'bwcompat_view') - -class TestForbiddenDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, view, **kw): - from pyramid.zcml import forbidden - return forbidden(context, view, **kw) - - def test_it(self): - from zope.interface import implementedBy - from pyramid.interfaces import IRequest - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.exceptions import Forbidden - reg = self.config.registry - context = self.config._ctx - def view(request): - return 'OK' - self._callFUT(context, view) - actions = extract_actions(context.actions) - - self.assertEqual(len(actions), 1) - - discrim = ('view', Forbidden, '', None, IView, None, None, None, None, - None, False, None, None, None) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], discrim) - register = regadapt['callable'] - register() - derived_view = reg.adapters.lookup( - (IViewClassifier, IRequest, implementedBy(Forbidden)), - IView, default=None) - - self.assertNotEqual(derived_view, None) - self.assertEqual(derived_view(None, None), 'OK') - self.assertEqual(derived_view.__name__, 'bwcompat_view') - - def test_it_with_dotted_renderer(self): - from zope.interface import implementedBy - from pyramid.interfaces import IRequest - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.exceptions import Forbidden - from pyramid.config import Configurator - reg = self.config.registry - config = Configurator(reg) - def dummy_renderer_factory(*arg, **kw): - return lambda *arg, **kw: 'OK' - config.add_renderer('.pt', dummy_renderer_factory) - config.commit() - def view(request): - return {} - context = self.config._ctx - self._callFUT(context, view, renderer='fake.pt') - actions = extract_actions(context.actions) - regadapt = actions[0] - register = regadapt['callable'] - register() - derived_view = reg.adapters.lookup( - (IViewClassifier, IRequest, implementedBy(Forbidden)), - IView, default=None) - self.assertNotEqual(derived_view, None) - self.assertEqual(derived_view(None, None).body, 'OK') - self.assertEqual(derived_view.__name__, 'bwcompat_view') - -class TestRepozeWho1AuthenticationPolicyDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, **kw): - from pyramid.zcml import repozewho1authenticationpolicy - return repozewho1authenticationpolicy(context, **kw) - - def test_it_defaults(self): - reg = self.config.registry - from pyramid.interfaces import IAuthenticationPolicy - context = self.config._ctx - self._callFUT(context) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthenticationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthenticationPolicy) - self.assertEqual(policy.callback, None) - self.assertEqual(policy.identifier_name, 'auth_tkt') - - def test_it(self): - reg = self.config.registry - from pyramid.interfaces import IAuthenticationPolicy - context = self.config._ctx - def callback(identity, request): - """ """ - self._callFUT(context, identifier_name='something', callback=callback) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthenticationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthenticationPolicy) - self.assertEqual(policy.callback, callback) - self.assertEqual(policy.identifier_name, 'something') - -class TestRemoteUserAuthenticationPolicyDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, **kw): - from pyramid.zcml import remoteuserauthenticationpolicy - return remoteuserauthenticationpolicy(context, **kw) - - def test_defaults(self): - from pyramid.interfaces import IAuthenticationPolicy - reg = self.config.registry - context = self.config._ctx - def callback(identity, request): - """ """ - self._callFUT(context) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthenticationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthenticationPolicy) - self.assertEqual(policy.environ_key, 'REMOTE_USER') - self.assertEqual(policy.callback, None) - - def test_it(self): - from pyramid.interfaces import IAuthenticationPolicy - reg = self.config.registry - context = self.config._ctx - def callback(identity, request): - """ """ - self._callFUT(context, environ_key='BLAH', callback=callback) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthenticationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthenticationPolicy) - self.assertEqual(policy.environ_key, 'BLAH') - self.assertEqual(policy.callback, callback) - -class TestAuthTktAuthenticationPolicyDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, secret, **kw): - from pyramid.zcml import authtktauthenticationpolicy - return authtktauthenticationpolicy(context, secret, **kw) - - def test_it_defaults(self): - from pyramid.interfaces import IAuthenticationPolicy - reg = self.config.registry - context = self.config._ctx - self._callFUT(context, 'sosecret') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthenticationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthenticationPolicy) - self.assertEqual(policy.cookie.secret, 'sosecret') - self.assertEqual(policy.callback, None) - - def test_it_noconfigerror(self): - from pyramid.interfaces import IAuthenticationPolicy - reg = self.config.registry - context = self.config._ctx - def callback(identity, request): - """ """ - self._callFUT(context, 'sosecret', callback=callback, - cookie_name='auth_tkt', - secure=True, include_ip=True, timeout=100, - reissue_time=60, http_only=True, path="/sub/") - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthenticationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthenticationPolicy) - self.assertEqual(policy.cookie.path, '/sub/') - self.assertEqual(policy.cookie.http_only, True) - self.assertEqual(policy.cookie.secret, 'sosecret') - self.assertEqual(policy.callback, callback) - - def test_it_configerror(self): - from pyramid.exceptions import ConfigurationError - context = self.config._ctx - def callback(identity, request): - """ """ - self.assertRaises(ConfigurationError, - self._callFUT, - context, 'sosecret', callback=callback, - cookie_name='auth_tkt', - secure=True, include_ip=True, timeout=100, - reissue_time=500, http_only=True, - path="/cgi-bin/app.cgi/") - -class TestACLAuthorizationPolicyDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, **kw): - from pyramid.zcml import aclauthorizationpolicy - return aclauthorizationpolicy(context, **kw) - - def test_it(self): - from pyramid.authorization import ACLAuthorizationPolicy - from pyramid.interfaces import IAuthorizationPolicy - reg = self.config.registry - context = self.config._ctx - def callback(identity, request): - """ """ - self._callFUT(context) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IAuthorizationPolicy) - self.assertEqual(regadapt['callable'], None) - self.assertEqual(regadapt['args'], ()) - policy = reg.getUtility(IAuthorizationPolicy) - self.assertEqual(policy.__class__, ACLAuthorizationPolicy) - -class TestRouteDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import route - return route(*arg, **kw) - - def _assertRoute(self, name, pattern, num_predicates=0): - from pyramid.interfaces import IRoutesMapper - reg = self.config.registry - mapper = reg.getUtility(IRoutesMapper) - routes = mapper.get_routes() - route = routes[0] - self.assertEqual(len(routes), 1) - self.assertEqual(route.name, name) - self.assertEqual(route.pattern, pattern) - self.assertEqual(len(routes[0].predicates), num_predicates) - return route - - def test_with_view(self): - from zope.interface import Interface - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRouteRequest - reg = self.config.registry - context = self.config._ctx - view = lambda *arg: 'OK' - self._callFUT(context, 'name', 'pattern', view=view) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 2) - - view_action = actions[0] - request_type = reg.getUtility(IRouteRequest, 'name') - view_discriminator = view_action['discriminator'] - discrim = ('view', None, '', None, IView, None, None, None, 'name', - None, False, None, None, None) - self.assertEqual(view_discriminator, discrim) - view_action['callable'](*view_action['args'], **view_action['kw']) - - route_action = actions[1] - route_discriminator = route_action['discriminator'] - self.assertEqual(route_discriminator, - ('route', 'name', False, None, None, None, None,None)) - self._assertRoute('name', 'pattern') - - wrapped = reg.adapters.lookup( - (IViewClassifier, request_type, Interface), IView, name='') - self.failUnless(wrapped) - - def test_with_view_and_view_context(self): - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRouteRequest - reg = self.config.registry - context = self.config._ctx - view = lambda *arg: 'OK' - self._callFUT(context, 'name', 'pattern', view=view, - view_context=IDummy) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 2) - - view_action = actions[0] - request_type = reg.getUtility(IRouteRequest, 'name') - view_discriminator = view_action['discriminator'] - discrim = ('view', IDummy, '', None, IView, None, None, None, 'name', - None, False, None, None, None) - self.assertEqual(view_discriminator, discrim) - view_action['callable'](*view_action['args'], **view_action['kw']) - - route_action = actions[1] - route_discriminator = route_action['discriminator'] - self.assertEqual(route_discriminator, - ('route', 'name', False, None, None, None, None,None)) - - self._assertRoute('name', 'pattern') - wrapped = reg.adapters.lookup( - (IViewClassifier, request_type, IDummy), IView, name='') - self.failUnless(wrapped) - - def test_with_view_context_trumps_view_for(self): - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRouteRequest - reg = self.config.registry - context = self.config._ctx - view = lambda *arg: 'OK' - class Foo: - pass - self._callFUT(context, 'name', 'pattern', view=view, - view_context=IDummy, view_for=Foo) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 2) - - view_action = actions[0] - request_type = reg.getUtility(IRouteRequest, 'name') - view_discriminator = view_action['discriminator'] - discrim = ('view', IDummy, '', None, IView, None, None, None, 'name', - None, False, None, None, None) - self.assertEqual(view_discriminator, discrim) - view_action['callable'](*view_action['args'], **view_action['kw']) - - route_action = actions[1] - route_discriminator = route_action['discriminator'] - self.assertEqual(route_discriminator, - ('route', 'name', False, None, None, None, None,None)) - - self._assertRoute('name', 'pattern') - wrapped = reg.adapters.lookup( - (IViewClassifier, request_type, IDummy), IView, name='') - self.failUnless(wrapped) - - def test_with_dotted_renderer(self): - from zope.interface import Interface - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRouteRequest - from pyramid.interfaces import IRendererFactory - reg = self.config.registry - def renderer(path): - return lambda *arg: 'OK' - reg.registerUtility(renderer, IRendererFactory, name='.pt') - context = self.config._ctx - - view = lambda *arg: 'OK' - self._callFUT(context, 'name', 'pattern', view=view, - renderer='fixtureapp/templates/foo.pt') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 2) - - view_action = actions[0] - request_type = reg.getUtility(IRouteRequest, 'name') - view_discriminator = view_action['discriminator'] - discrim = ('view', None, '', None, IView, None, None, None, 'name', - None, False, None, None, None) - self.assertEqual(view_discriminator, discrim) - view_action['callable'](*view_action['args'], **view_action['kw']) - - route_action = actions[1] - route_discriminator = route_action['discriminator'] - self.assertEqual(route_discriminator, - ('route', 'name', False, None, None, None, None,None)) - self._assertRoute('name', 'pattern') - - wrapped = reg.adapters.lookup( - (IViewClassifier, request_type, Interface), IView, name='') - self.failUnless(wrapped) - request = DummyRequest() - result = wrapped(None, request) - self.assertEqual(result.body, 'OK') - - def test_with_custom_predicates(self): - def pred1(context, request): pass - def pred2(context, request): pass - preds = tuple(sorted([pred1, pred2])) - - context = self.config._ctx - - self._callFUT(context, 'name', 'pattern', - custom_predicates=(pred1, pred2)) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - - route_action = actions[0] - route_discriminator = route_action['discriminator'] - self.assertEqual( - route_discriminator, - ('route', 'name', False, None, None, None, None,None) + preds) - self._assertRoute('name', 'pattern', 2) - - def test_with_path_argument_no_pattern(self): - context = self.config._ctx - self._callFUT(context, 'name', path='pattern') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - - route_action = actions[0] - route_discriminator = route_action['discriminator'] - self.assertEqual(route_discriminator, - ('route', 'name', False, None, None, None, None,None)) - self._assertRoute('name', 'pattern') - - def test_with_path_argument_and_pattern(self): - context = self.config._ctx - self._callFUT(context, 'name', pattern='pattern', path='path') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - - route_action = actions[0] - route_discriminator = route_action['discriminator'] - self.assertEqual(route_discriminator, - ('route', 'name', False, None, None, None, None,None)) - self._assertRoute('name', 'pattern') - - - def test_with_neither_path_nor_pattern(self): - from pyramid.exceptions import ConfigurationError - context = self.config._ctx - self.assertRaises(ConfigurationError, self._callFUT, context, 'name') - -class TestStaticDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import static - return static(*arg, **kw) - - def test_it_with_slash(self): - from pyramid import testing - testing.registerDummySecurityPolicy(permissive=False) - from pyramid.static import PackageURLParser - from zope.interface import implementedBy - from pyramid.static import StaticURLInfo - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRouteRequest - from pyramid.interfaces import IRoutesMapper - reg = self.config.registry - context = self.config._ctx - - self._callFUT(context, 'name', 'fixtures/static') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 2) - - view_action = actions[0] - discriminator = view_action['discriminator'] - self.assertEqual(discriminator[:3], ('view', StaticURLInfo, '')) - self.assertEqual(discriminator[4], IView) - view_action['callable'](*view_action['args'], **view_action['kw']) - - route_action = actions[1] - discriminator = route_action['discriminator'] - self.assertEqual( - discriminator, - ('route', 'name/', False, None, None, None, None, None) - ) - - mapper = reg.getUtility(IRoutesMapper) - routes = mapper.get_routes() - self.assertEqual(len(routes), 1) - self.assertEqual(routes[0].pattern, 'name/*subpath') - self.assertEqual(routes[0].name, 'name/') - - iface = implementedBy(StaticURLInfo) - request_type = reg.getUtility(IRouteRequest, 'name/') - view = reg.adapters.lookup( - (IViewClassifier, request_type, iface), IView, name='') - request = DummyRequest() - self.assertEqual(view(None, request).__class__, PackageURLParser) - - def test_it_with_nondefault_permission(self): - from pyramid import testing - from pyramid.exceptions import Forbidden - testing.registerDummySecurityPolicy(permissive=False) - from zope.interface import implementedBy - from pyramid.static import StaticURLInfo - from pyramid.interfaces import IView - from pyramid.interfaces import IViewClassifier - from pyramid.interfaces import IRouteRequest - from pyramid.interfaces import IRoutesMapper - reg = self.config.registry - context = self.config._ctx - self._callFUT(context, 'name', 'fixtures/static', permission='aperm') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 2) - - view_action = actions[0] - discriminator = view_action['discriminator'] - self.assertEqual(discriminator[:3], ('view', StaticURLInfo, '')) - self.assertEqual(discriminator[4], IView) - view_action['callable'](*view_action['args'], **view_action['kw']) - - route_action = actions[1] - discriminator = route_action['discriminator'] - self.assertEqual( - discriminator, - ('route', 'name/', False, None, None, None, None, None)) - mapper = reg.getUtility(IRoutesMapper) - routes = mapper.get_routes() - self.assertEqual(len(routes), 1) - self.assertEqual(routes[0].pattern, 'name/*subpath') - self.assertEqual(routes[0].name, 'name/') - - - iface = implementedBy(StaticURLInfo) - request_type = reg.getUtility(IRouteRequest, 'name/') - view = reg.adapters.lookup( - (IViewClassifier, request_type, iface), IView, name='') - request = DummyRequest() - self.assertRaises(Forbidden, view, None, request) - -class TestAssetDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import asset - return asset(*arg, **kw) - - def test_it(self): - import pyramid.tests - context = self.config._ctx - L = [] - def dummy_override(*arg): - L.append(arg) - self._callFUT(context, 'pyramid.tests:fixtures/', - 'pyramid.tests:fixtureapp/', _override=dummy_override) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - action = actions[0] - self.assertEqual(action['discriminator'], None) - action['callable']() - self.assertEqual( - L, - [(pyramid.tests, 'fixtures/', pyramid.tests, 'fixtureapp/')]) - - -class TestRendererDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import renderer - return renderer(*arg, **kw) - - def test_it(self): - from pyramid.interfaces import IRendererFactory - reg = self.config.registry - context = self.config._ctx - renderer = lambda *arg, **kw: None - self._callFUT(context, renderer, 'r') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - action = actions[0] - self.assertEqual(action['discriminator'], (IRendererFactory, 'r')) - self.failUnless(reg.getUtility(IRendererFactory, 'r'), renderer) - -class TestZCMLConfigure(unittest.TestCase): - i = 0 - def _callFUT(self, path, package): - from pyramid.zcml import zcml_configure - return zcml_configure(path, package) - - def setUp(self): - from zope.deprecation import __show__ - __show__.off() - testing.setUp(autocommit=False) - self.tempdir = None - import sys - import os - import tempfile - from pyramid.path import package_path - from pyramid.tests import fixtureapp as package - import shutil - tempdir = tempfile.mkdtemp() - modname = 'myfixture%s' % self.i - self.i += 1 - self.packagepath = os.path.join(tempdir, modname) - fixturedir = package_path(package) - shutil.copytree(fixturedir, self.packagepath) - sys.path.insert(0, tempdir) - self.module = __import__(modname) - self.tempdir = tempdir - - def tearDown(self): - from zope.deprecation import __show__ - __show__.on() - testing.tearDown() - import sys - import shutil - if self.module is not None: - del sys.modules[self.module.__name__] - if self.tempdir is not None: - sys.path.pop(0) - shutil.rmtree(self.tempdir) - - def test_zcml_configure(self): - actions = self._callFUT('configure.zcml', self.module) - self.failUnless(actions) - self.failUnless(isinstance(actions, list)) - - def test_zcml_configure_nonexistent_configure_dot_zcml(self): - import os - os.remove(os.path.join(self.packagepath, 'configure.zcml')) - self.assertRaises(IOError, self._callFUT, 'configure.zcml', - self.module) - -class TestZCMLScanDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, package): - from pyramid.zcml import scan - return scan(context, package) - - def test_it(self): - dummy_module = DummyModule() - def foo(): pass - def bar(scanner, name, ob): - dummy_module.scanned = True - foo.__venusian_callbacks__ = {'pyramid':[bar]} - dummy_module.foo = foo - - context = self.config._ctx - self._callFUT(context, dummy_module) - self.assertEqual(dummy_module.scanned, True) - -class TestAdapterDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import adapter - return adapter(*arg, **kw) - - def test_for_is_None_no_adaptedBy(self): - context = DummyContext() - factory = DummyFactory() - self.assertRaises(TypeError, self._callFUT, context, [factory], - provides=None, for_=None) - - def test_for_is_None_adaptedBy_still_None(self): - context = DummyContext() - factory = DummyFactory() - factory.__component_adapts__ = None - self.assertRaises(TypeError, self._callFUT, context, [factory], - provides=None, for_=None) - - def test_for_is_None_adaptedBy_set(self): - from pyramid.registry import Registry - context = DummyContext() - context.registry = self.config.registry - factory = DummyFactory() - factory.__component_adapts__ = (IDummy,) - self._callFUT(context, [factory], provides=IFactory, for_=None) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], - ('adapter', (IDummy,), IFactory, '')) - self.assertEqual(regadapt['callable'].im_func, - Registry.registerAdapter.im_func) - self.assertEqual(regadapt['args'], - (factory, (IDummy,), IFactory, '', None)) - - def test_provides_missing(self): - context = DummyContext() - factory = DummyFactory() - self.assertRaises(TypeError, self._callFUT, context, [factory], - provides=None, for_=(IDummy,)) - - def test_provides_obtained_via_implementedBy(self): - from pyramid.registry import Registry - context = DummyContext() - context.registry = self.config.registry - self._callFUT(context, [DummyFactory], for_=(IDummy,)) - regadapt = extract_actions(context.actions)[0] - self.assertEqual(regadapt['discriminator'], - ('adapter', (IDummy,), IFactory, '')) - self.assertEqual(regadapt['callable'].im_func, - Registry.registerAdapter.im_func) - self.assertEqual(regadapt['args'], - (DummyFactory, (IDummy,), IFactory, '', None)) - - def test_multiple_factories_multiple_for(self): - context = DummyContext() - factory = DummyFactory() - self.assertRaises(ValueError, self._callFUT, context, - [factory, factory], - provides=IFactory, - for_=(IDummy, IDummy)) - - def test_no_factories_multiple_for(self): - context = DummyContext() - self.assertRaises(ValueError, self._callFUT, context, - factory=[], - provides=IFactory, - for_=(IDummy, IDummy)) - - def test_rolled_up_factories(self): - from pyramid.registry import Registry - context = DummyContext() - context.registry = self.config.registry - factory = DummyFactory() - self._callFUT(context, - [factory, factory], - provides=IFactory, - for_=(IDummy,)) - regadapt = extract_actions(context.actions)[0] - self.assertEqual(regadapt['discriminator'], - ('adapter', (IDummy,), IFactory, '')) - self.assertEqual(regadapt['callable'].im_func, - Registry.registerAdapter.im_func) - self.assertEqual(regadapt['args'][0].__module__, 'pyramid.zcml') - -class TestSubscriberDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import subscriber - return subscriber(*arg, **kw) - - def test_no_factory_no_handler(self): - context = self.config._ctx - self.assertRaises(TypeError, - self._callFUT, context, for_=None, factory=None, - handler=None, - provides=None) - - def test_handler_with_provides(self): - context = self.config._ctx - self.assertRaises(TypeError, - self._callFUT, context, for_=None, factory=None, - handler=1, provides=1) - - def test_handler_and_factory(self): - context = self.config._ctx - self.assertRaises(TypeError, - self._callFUT, context, for_=None, factory=1, - handler=1, provides=None) - - def test_no_provides_with_factory(self): - context = self.config._ctx - self.assertRaises(TypeError, - self._callFUT, context, for_=None, factory=1, - handler=None, provides=None) - - def test_adapted_by_as_for_is_None(self): - context = self.config._ctx - factory = DummyFactory() - factory.__component_adapts__ = None - self.assertRaises(TypeError, self._callFUT, context, for_=None, - factory=factory, handler=None, provides=IFactory) - - def test_register_with_factory(self): - context = self.config._ctx - factory = DummyFactory() - self._callFUT(context, for_=(IDummy,), - factory=factory, handler=None, provides=IFactory) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - subadapt = actions[0] - self.assertEqual(subadapt['discriminator'], None) - subadapt['callable'](*subadapt['args'], **subadapt['kw']) - registrations = self.config.registry._subscription_registrations - self.assertEqual(len(registrations), 1) - reg = registrations[0] - self.assertEqual( - reg[:4], - ((IDummy,), IFactory, None, factory) - ) - - def test_register_with_handler(self): - context = self.config._ctx - factory = DummyFactory() - self._callFUT(context, for_=(IDummy,), - factory=None, handler=factory) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - subadapt = actions[0] - self.assertEqual(subadapt['discriminator'], None) - subadapt['callable'](*subadapt['args'], **subadapt['kw']) - registrations = self.config.registry._handler_registrations - self.assertEqual(len(registrations), 1) - self.assertEqual( - registrations[0][:3], - ((IDummy,), u'', factory) - ) - -class TestUtilityDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import utility - return utility(*arg, **kw) - - def test_factory_and_component(self): - context = self.config._ctx - self.assertRaises(TypeError, self._callFUT, - context, factory=1, component=1) - - def test_missing_provides(self): - context = self.config._ctx - self.assertRaises(TypeError, self._callFUT, context, provides=None) - - def test_provides_from_factory_implements(self): - from pyramid.registry import Registry - context = self.config._ctx - self._callFUT(context, factory=DummyFactory) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - utility = actions[0] - self.assertEqual(utility['discriminator'], ('utility', IFactory, '')) - self.assertEqual(utility['callable'].im_func, - Registry.registerUtility.im_func) - self.assertEqual(utility['args'][:3], (None, IFactory, '')) - self.assertEqual(utility['kw'], {'factory':DummyFactory}) - - def test_provides_from_component_provides(self): - from pyramid.registry import Registry - context = self.config._ctx - component = DummyFactory() - self._callFUT(context, component=component) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - utility = actions[0] - self.assertEqual(utility['discriminator'], ('utility', IFactory, '')) - self.assertEqual(utility['callable'].im_func, - Registry.registerUtility.im_func) - self.assertEqual(utility['args'][:3], (component, IFactory, '')) - self.assertEqual(utility['kw'], {}) - -class TestTranslationDirDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import translationdir - return translationdir(*arg, **kw) - - def test_it(self): - import os - here = os.path.dirname(__file__) - expected = os.path.join(here, 'localeapp', 'locale') - from pyramid.interfaces import ITranslationDirectories - context = self.config._ctx - tdir = 'pyramid.tests.localeapp:locale' - self._callFUT(context, tdir) - util = self.config.registry.getUtility(ITranslationDirectories) - self.assertEqual(util, [expected]) - -class TestLocaleNegotiatorDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, *arg, **kw): - from pyramid.zcml import localenegotiator - return localenegotiator(*arg, **kw) - - def test_it(self): - from pyramid.interfaces import ILocaleNegotiator - context = self.config._ctx - dummy_negotiator = object() - self._callFUT(context, dummy_negotiator) - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - action = actions[0] - self.assertEqual(action['discriminator'], ILocaleNegotiator) - callback = action['callable'] - callback() - self.assertEqual(self.config.registry.getUtility(ILocaleNegotiator), - dummy_negotiator) - -class TestDefaultPermissionDirective(unittest.TestCase): - def setUp(self): - self.config = testing.setUp(autocommit=False) - self.config._ctx = self.config._make_context() - - def tearDown(self): - testing.tearDown() - - def _callFUT(self, context, name): - from pyramid.zcml import default_permission - return default_permission(context, name) - - def test_it(self): - from pyramid.interfaces import IDefaultPermission - reg = self.config.registry - context = self.config._ctx - self._callFUT(context, 'view') - actions = extract_actions(context.actions) - self.assertEqual(len(actions), 1) - regadapt = actions[0] - self.assertEqual(regadapt['discriminator'], IDefaultPermission) - perm = reg.getUtility(IDefaultPermission) - self.assertEqual(perm, 'view') - -class TestLoadZCML(unittest.TestCase): - def setUp(self): - testing.setUp(autocommit=False) - - def tearDown(self): - testing.tearDown() - - def test_it(self): - from zope.configuration import xmlconfig - import pyramid.includes - xmlconfig.file('configure.zcml', package=pyramid.includes) - -class TestRolledUpFactory(unittest.TestCase): - def _callFUT(self, *factories): - from pyramid.zcml import _rolledUpFactory - return _rolledUpFactory(factories) - - def test_it(self): - def foo(ob): - return ob - factory = self._callFUT(foo, foo) - result = factory(True) - self.assertEqual(result, True) - -class Test_path_spec(unittest.TestCase): - def _callFUT(self, context, path): - from pyramid.zcml import path_spec - return path_spec(context, path) - - def test_no_package_attr(self): - context = DummyContext() - path = '/thepath' - result = self._callFUT(context, path) - self.assertEqual(result, path) - - def test_package_attr_None(self): - context = DummyContext() - context.package = None - path = '/thepath' - result = self._callFUT(context, path) - self.assertEqual(result, path) - - def test_package_path_doesnt_start_with_abspath(self): - context = DummyContext() - context.package = DummyPackage('pyramid.tests') - path = '/thepath' - result = self._callFUT(context, path) - self.assertEqual(result, path) - - def test_package_path_starts_with_abspath(self): - import pkg_resources - import os - context = DummyContext() - package = DummyPackage('pyramid.tests') - package_path = pkg_resources.resource_filename('pyramid.tests', '') - template_path = os.path.join(package_path, 'templates/foo.pt') - context.package = package - result = self._callFUT(context, template_path) - self.assertEqual(result, 'pyramid.tests:templates/foo.pt') - - def test_package_name_is___main__(self): - context = DummyContext() - package = DummyPackage('__main__') - context.package = package - result = self._callFUT(context, '/foo.pt') - self.assertEqual(result, '/foo.pt') - - def test_path_is_already_asset_spec(self): - context = DummyContext() - result = self._callFUT(context, 'pyramid.tests:foo.pt') - self.assertEqual(result, 'pyramid.tests:foo.pt') - -class IDummy(Interface): - pass - -class IFactory(Interface): - pass - -class DummyFactory(object): - implements(IFactory) - def __call__(self): - """ """ - -class DummyModule: - __path__ = "foo" - __name__ = "dummy" - __file__ = '' - -class DummyContext: - def __init__(self, resolved=DummyModule): - self.actions = [] - self.info = None - self.resolved = resolved - self.package = None - - def action(self, discriminator, callable=None, args=(), kw={}, order=0): - self.actions.append((discriminator, callable, args, kw, order)) - - def path(self, path): - return path - -class Dummy: - pass - -class DummyRoute: - pass - -class DummyRequest: - subpath = () - def __init__(self, environ=None): - if environ is None: - environ = {} - self.environ = environ - self.path_info = environ.get('PATH_INFO', None) - - def get_response(self, app): - return app - - def copy(self): - return self - -class DummyPackage(object): - def __init__(self, name): - self.__name__ = name - self.__file__ = '/__init__.py' - -def extract_actions(native): - from zope.configuration.config import expand_action - L = [] - for action in native: - (discriminator, callable, args, kw, includepath, info, order - ) = expand_action(*action) - d = {} - d['discriminator'] = discriminator - d['callable'] = callable - d['args'] = args - d['kw'] = kw - d['order'] = order - L.append(d) - return L - diff --git a/pyramid/tests/viewdecoratorapp/__init__.py b/pyramid/tests/viewdecoratorapp/__init__.py index 5bb534f79..ad2890d92 100644 --- a/pyramid/tests/viewdecoratorapp/__init__.py +++ b/pyramid/tests/viewdecoratorapp/__init__.py @@ -1 +1,3 @@ -# package +def includeme(config): + config.scan('pyramid.tests.viewdecoratorapp') + diff --git a/pyramid/tests/viewdecoratorapp/configure.zcml b/pyramid/tests/viewdecoratorapp/configure.zcml deleted file mode 100644 index 169c42128..000000000 --- a/pyramid/tests/viewdecoratorapp/configure.zcml +++ /dev/null @@ -1,6 +0,0 @@ -<configure xmlns="http://pylonshq.com/pyramid"> - - <include package="pyramid.includes" /> - <scan package="."/> - -</configure> diff --git a/pyramid/url.py b/pyramid/url.py index f2507830d..87a12a1b3 100644 --- a/pyramid/url.py +++ b/pyramid/url.py @@ -321,8 +321,7 @@ def static_url(path, request, **kw): Generates a fully qualified URL for a static :term:`asset`. The asset must live within a location defined via the :meth:`pyramid.config.Configurator.add_static_view` - :term:`configuration declaration` or the ``<static>`` ZCML - directive (see :ref:`static_assets_section`). + :term:`configuration declaration` (see :ref:`static_assets_section`). .. note:: Calling :meth:`pyramid.Request.static_url` can be used to achieve the same result as :func:`pyramid.url.static_url`. diff --git a/pyramid/view.py b/pyramid/view.py index f1d8a33e3..310e6d58f 100644 --- a/pyramid/view.py +++ b/pyramid/view.py @@ -145,7 +145,7 @@ def is_response(ob): class view_config(object): """ A function, class or method :term:`decorator` which allows a developer to create view registrations nearer to a :term:`view - callable` definition than use of :term:`ZCML` or :term:`imperative + callable` definition than use :term:`imperative configuration` to do the same. For example, this code in a module ``views.py``:: @@ -165,16 +165,6 @@ class view_config(object): config.add_view(views.my_view, context=MyResource, name='my_view', permission='read', 'route_name='site1') - Or might replace the following ZCML ``view`` declaration:: - - <view - for='.resources.MyResource' - view='.views.my_view' - name='my_view' - permission='read' - route_name='site1' - /> - .. note: :class:`pyramid.view.view_config` is also importable, for backwards compatibility purposes, as the name :class:`pyramid.view.bfg_view`. @@ -368,17 +358,9 @@ class view_config(object): return Response('hello from %s!' % self.context) To make use of any ``view_config`` declaration, you must perform a - :term:`scan`. To do so, either insert the following boilerplate - into your application registry's ZCML:: + :term:`scan`. To do so, insert the following into your Pyramid + application's ``main`` stanza:: - <scan package="."/> - - See :ref:`scan_directive` for more information about the ZCML - ``scan`` directive. - - Or, if you don't use ZCML, use the - :meth:`pyramid.config.Configurator.scan` method:: - config.scan() """ venusian = venusian # for testing injection @@ -509,16 +491,8 @@ redirect to the slash-appended PATH_INFO. Note that this will *lose* ``POST`` data information (turning it into a GET), so you shouldn't rely on this to redirect POST requests. -If you use :term:`ZCML`, add the following to your application's -``configure.zcml`` to use this view as the Not Found view:: - - <view - context="pyramid.exceptions.NotFound" - view="pyramid.view.append_slash_notfound_view"/> - -Or use the -:meth:`pyramid.config.Configurator.add_view` -method if you don't use ZCML:: +Use the :meth:`pyramid.config.Configurator.add_view` method to configure this +view as the Not Found view:: from pyramid.exceptions import NotFound from pyramid.view import append_slash_notfound_view diff --git a/pyramid/wsgi.py b/pyramid/wsgi.py index 69a250534..a647175db 100644 --- a/pyramid/wsgi.py +++ b/pyramid/wsgi.py @@ -17,14 +17,7 @@ def wsgiapp(wrapped): ('Content-Length', len(body)) ] ) return [body] - Allows the following ZCML view declaration to be made:: - - <view - view=".views.hello_world" - name="hello_world.txt" - /> - - Or the following call to + Allows the following call to :meth:`pyramid.config.Configurator.add_view`:: from views import hello_world @@ -56,14 +49,7 @@ def wsgiapp2(wrapped): ('Content-Length', len(body)) ] ) return [body] - Allows the following ZCML view declaration to be made:: - - <view - view=".views.hello_world" - name="hello_world.txt" - /> - - Or the following call to + Allows the following call to :meth:`pyramid.config.Configurator.add_view`:: from views import hello_world diff --git a/pyramid/zcml.py b/pyramid/zcml.py deleted file mode 100644 index 9eceee244..000000000 --- a/pyramid/zcml.py +++ /dev/null @@ -1,791 +0,0 @@ -import os - -from zope.configuration.fields import GlobalInterface -from zope.configuration.fields import GlobalObject -from zope.configuration.fields import Tokens - -from zope.deprecation import deprecated - -from zope.interface import Interface -from zope.interface import implementedBy -from zope.interface import providedBy - -from zope.schema import ASCIILine -from zope.schema import Bool -from zope.schema import Int -from zope.schema import TextLine - -from pyramid.authentication import AuthTktAuthenticationPolicy -from pyramid.authentication import RemoteUserAuthenticationPolicy -from pyramid.authentication import RepozeWho1AuthenticationPolicy -from pyramid.authorization import ACLAuthorizationPolicy -from pyramid.config import Configurator -from pyramid.exceptions import ConfigurationError -from pyramid.asset import asset_spec_from_abspath -from pyramid.threadlocal import get_current_registry - -###################### directives ########################## - -class IViewDirective(Interface): - context = GlobalObject( - title=u"The interface or class this view is for.", - required=False - ) - - for_ = GlobalObject( - title=(u"The interface or class this view is for (alternate spelling " - "of ``context``)."), - required=False - ) - - permission = TextLine( - title=u"Permission", - description=u"The permission needed to use the view.", - required=False - ) - - view = GlobalObject( - title=u"", - description=u"The view function", - required=False, - ) - - name = TextLine( - title=u"The name of the view", - description=u""" - The name shows up in URLs/paths. For example 'foo' or 'foo.html'.""", - required=False, - ) - - attr = TextLine( - title=u'The callable attribute of the view object(default is __call__)', - description=u'', - required=False) - - renderer = TextLine( - title=u'The renderer asssociated with the view', - description=u'', - required=False) - - wrapper = TextLine( - title = u'The *name* of the view that acts as a wrapper for this view.', - description = u'', - required=False) - - request_type = GlobalObject( - title=u"The dotted name interface for the request type", - description=(u"The view will be called if the interface represented by " - u"'request_type' is implemented by the request. The " - u"default request type is pyramid.interfaces.IRequest"), - required=False - ) - - route_name = TextLine( - title = u'The route that must match for this view to be used', - required = False) - - containment = GlobalObject( - title = u'Dotted name of a containment class or interface', - required=False) - - request_method = TextLine( - title = u'Request method name that must be matched (e.g. GET/POST)', - description = (u'The view will be called if and only if the request ' - 'method (``request.method``) matches this string.'), - required=False) - - request_param = TextLine( - title = (u'Request parameter name that must exist in ' - '``request.params`` for this view to match'), - description = (u'The view will be called if and only if the request ' - 'parameter exists which matches this string.'), - required=False) - - xhr = Bool( - title = (u'True if request has an X-Requested-With header with the ' - 'value "XMLHttpRequest"'), - description=(u'Useful for detecting AJAX requests issued from ' - 'jQuery, Protoype and other JavaScript libraries'), - required=False) - - accept = TextLine( - title = (u'Mimetype(s) that must be present in "Accept" HTTP header ' - 'for the view to match a request'), - description=(u'Accepts a mimetype match token in the form ' - '"text/plain", a wildcard mimetype match token in the ' - 'form "text/*" or a match-all wildcard mimetype match ' - 'token in the form "*/*".'), - required = False) - - header = TextLine( - title=u'Header name/value pair in the form "name=<regex>"', - description=u'Regular expression matching for header values', - required = False) - - path_info = TextLine( - title = (u'Regular expression which must match the ``PATH_INFO`` ' - 'header for the view to match a request'), - description=(u'Accepts a regular expression.'), - required = False) - - decorator = GlobalObject( - title = u'View decorator', - required = False) - - mapper = GlobalObject( - title = u'View mapper', - required = False) - - custom_predicates = Tokens( - title=u"One or more custom dotted names to custom predicate callables", - description=(u"A list of dotted name references to callables that " - "will be used as predicates for this view configuration"), - required=False, - value_type=GlobalObject() - ) - - -def view( - _context, - permission=None, - for_=None, - view=None, - name="", - request_type=None, - route_name=None, - request_method=None, - request_param=None, - containment=None, - attr=None, - renderer=None, - wrapper=None, - xhr=False, - accept=None, - header=None, - path_info=None, - traverse=None, - decorator=None, - mapper=None, - custom_predicates=(), - context=None, - cacheable=True, # not used, here for b/w compat < 0.8 - ): - - context = context or for_ - config = Configurator.with_context(_context) - config.add_view( - permission=permission, context=context, view=view, name=name, - request_type=request_type, route_name=route_name, - request_method=request_method, request_param=request_param, - containment=containment, attr=attr, renderer=renderer, - wrapper=wrapper, xhr=xhr, accept=accept, header=header, - path_info=path_info, custom_predicates=custom_predicates, - decorator=decorator, mapper=mapper) - -_view = view # for directives that take a view arg - - -class IRouteLikeDirective(Interface): - """ The interface for the ``route`` ZCML directive - """ - pattern = TextLine(title=u'pattern', required=False) - factory = GlobalObject(title=u'context factory', required=False) - view = GlobalObject(title=u'view', required=False) - - view_context = GlobalObject(title=u'view_context', required=False) - # aliases for view_context - for_ = GlobalObject(title=u'for', required=False) - view_for = GlobalObject(title=u'view_for', required=False) - - view_permission = TextLine(title=u'view_permission', required=False) - # alias for view_permission - permission = TextLine(title=u'permission', required=False) - - view_renderer = TextLine(title=u'view_renderer', required=False) - # alias for view_renderer - renderer = TextLine(title=u'renderer', required=False) - - view_attr = TextLine(title=u'view_attr', required=False) - - request_method = TextLine(title=u'request_method', required=False) - request_param = TextLine(title=u'request_param', required=False) - header = TextLine(title=u'header', required=False) - accept = TextLine(title=u'accept', required=False) - xhr = Bool(title=u'xhr', required=False) - path_info = TextLine(title=u'path_info', required=False) - - traverse = TextLine( - title=u'Traverse pattern"', - description=u'A pattern which will compose a traversal path', - required = False) - - custom_predicates = Tokens( - title=u"One or more custom dotted names to custom predicate callables", - description=(u"A list of dotted name references to callables that " - "will be used as predicates for this view configuration"), - required=False, - value_type=GlobalObject() - ) - use_global_views = Bool(title=u'use_global_views', required=False) - -class IRouteDirective(IRouteLikeDirective): - name = TextLine(title=u'name', required=True) - # alias for pattern - path = TextLine(title=u'path', required=False) - -def route(_context, - name, - pattern=None, - view=None, - view_for=None, - permission=None, - factory=None, - for_=None, - header=None, - xhr=False, - accept=None, - path_info=None, - request_method=None, - request_param=None, - custom_predicates=(), - view_permission=None, - view_attr=None, - renderer=None, - view_renderer=None, - view_context=None, - traverse=None, - use_global_views=False, - path=None): - """ Handle ``route`` ZCML directives - """ - # the strange ordering of the request kw args above is for b/w - # compatibility purposes. - - # these are route predicates; if they do not match, the next route - # in the routelist will be tried - if view_context is None: - view_context = view_for or for_ - - view_permission = view_permission or permission - view_renderer = view_renderer or renderer - - if pattern is None: - pattern = path - - if pattern is None: - raise ConfigurationError('route directive must include a "pattern"') - - config = Configurator.with_context(_context) - config.add_route( - name, - pattern, - factory=factory, - header=header, - xhr=xhr, - accept=accept, - path_info=path_info, - request_method=request_method, - request_param=request_param, - custom_predicates=custom_predicates, - view=view, - view_context=view_context, - view_permission=view_permission, - view_renderer=view_renderer, - view_attr=view_attr, - use_global_views=use_global_views, - traverse=traverse, - ) - -class ISystemViewDirective(Interface): - view = GlobalObject( - title=u"", - description=u"The view function", - required=False, - ) - - attr = TextLine( - title=u'The callable attribute of the view object(default is __call__)', - description=u'', - required=False) - - renderer = TextLine( - title=u'The renderer asssociated with the view', - description=u'', - required=False) - - wrapper = TextLine( - title = u'The *name* of the view that acts as a wrapper for this view.', - description = u'', - required=False) - -def notfound(_context, - view=None, - attr=None, - renderer=None, - wrapper=None): - - config = Configurator.with_context(_context) - config.set_notfound_view(view=view, attr=attr, renderer=renderer, - wrapper=wrapper) - - -def forbidden(_context, - view=None, - attr=None, - renderer=None, - wrapper=None): - - config = Configurator.with_context(_context) - config.set_forbidden_view(view=view, attr=attr, renderer=renderer, - wrapper=wrapper) - - -class IAssetDirective(Interface): - """ - Directive for specifying that one package may override assets from - another package. - """ - to_override = TextLine( - title=u"Override spec", - description=u'The spec of the asset to override.', - required=True) - override_with = TextLine( - title=u"With spec", - description=u"The spec of the asset providing the override.", - required=True) - -def asset(_context, to_override, override_with, _override=None): - config = Configurator.with_context(_context) - config.override_asset(to_override, override_with, _override=_override) - -class IRepozeWho1AuthenticationPolicyDirective(Interface): - identifier_name = TextLine(title=u'identitfier_name', required=False, - default=u'auth_tkt') - callback = GlobalObject(title=u'callback', required=False) - -def repozewho1authenticationpolicy(_context, identifier_name='auth_tkt', - callback=None): - policy = RepozeWho1AuthenticationPolicy(identifier_name=identifier_name, - callback=callback) - # authentication policies must be registered eagerly so they can - # be found by the view registration machinery - config = Configurator.with_context(_context) - config._set_authentication_policy(policy) - -class IRemoteUserAuthenticationPolicyDirective(Interface): - environ_key = TextLine(title=u'environ_key', required=False, - default=u'REMOTE_USER') - callback = GlobalObject(title=u'callback', required=False) - -def remoteuserauthenticationpolicy(_context, environ_key='REMOTE_USER', - callback=None): - policy = RemoteUserAuthenticationPolicy(environ_key=environ_key, - callback=callback) - # authentication policies must be registered eagerly so they can - # be found by the view registration machinery - config = Configurator.with_context(_context) - config._set_authentication_policy(policy) - -class IAuthTktAuthenticationPolicyDirective(Interface): - secret = TextLine(title=u'secret', required=True) - callback = GlobalObject(title=u'callback', required=False) - cookie_name = ASCIILine(title=u'cookie_name', required=False, - default='auth_tkt') - secure = Bool(title=u"secure", required=False, default=False) - include_ip = Bool(title=u"include_ip", required=False, default=False) - timeout = Int(title=u"timeout", required=False, default=None) - reissue_time = Int(title=u"reissue_time", required=False, default=None) - max_age = Int(title=u"max_age", required=False, default=None) - path = ASCIILine(title=u"path", required=False, default='/') - http_only = Bool(title=u"http_only", required=False, default=False) - -def authtktauthenticationpolicy(_context, - secret, - callback=None, - cookie_name='auth_tkt', - secure=False, - include_ip=False, - timeout=None, - reissue_time=None, - max_age=None, - http_only=False, - path='/'): - try: - policy = AuthTktAuthenticationPolicy(secret, - callback=callback, - cookie_name=cookie_name, - secure=secure, - include_ip = include_ip, - timeout = timeout, - reissue_time = reissue_time, - max_age=max_age, - http_only=http_only, - path=path) - except ValueError, why: - raise ConfigurationError(str(why)) - # authentication policies must be registered eagerly so they can - # be found by the view registration machinery - config = Configurator.with_context(_context) - config._set_authentication_policy(policy) - -class IACLAuthorizationPolicyDirective(Interface): - pass - -def aclauthorizationpolicy(_context): - policy = ACLAuthorizationPolicy() - # authorization policies must be registered eagerly so they can be - # found by the view registration machinery - config = Configurator.with_context(_context) - config._set_authorization_policy(policy) - -class IRendererDirective(Interface): - factory = GlobalObject( - title=u'IRendererFactory implementation', - required=True) - - name = TextLine( - title=u'Token (e.g. ``json``) or filename extension (e.g. ".pt")', - required=False) - -def renderer(_context, factory, name=''): - # renderer factories must be registered eagerly so they can be - # found by the view machinery - config = Configurator.with_context(_context) - config.add_renderer(name, factory) - -class IStaticDirective(Interface): - name = TextLine( - title=u"The URL prefix of the static view", - description=u""" - The directory will be served up for the route that starts with - this prefix.""", - required=True) - - path = TextLine( - title=u'Path to the directory which contains assets', - description=u'May be package-relative by using a colon to ' - 'separate package name and path relative to the package directory.', - required=True) - - cache_max_age = Int( - title=u"Cache maximum age in seconds", - required=False, - default=None) - - permission = TextLine( - title=u'Permission string', - description = u'The permission string', - required = False) - -def static(_context, name, path, cache_max_age=3600, - permission='__no_permission_required__'): - """ Handle ``static`` ZCML directives - """ - config = Configurator.with_context(_context) - config.add_static_view(name, path, cache_max_age=cache_max_age, - permission=permission) - -class IScanDirective(Interface): - package = GlobalObject( - title=u"The package we'd like to scan.", - required=True, - ) - -def scan(_context, package): - config = Configurator.with_context(_context) - config.scan(package) - -class ITranslationDirDirective(Interface): - dir = TextLine( - title=u"Add a translation directory", - description=(u"Add a translation directory"), - required=True, - ) - -def translationdir(_context, dir): - path = path_spec(_context, dir) - config = Configurator.with_context(_context) - config.add_translation_dirs(path) - -class ILocaleNegotiatorDirective(Interface): - negotiator = GlobalObject( - title=u"Configure a locale negotiator", - description=(u'Configure a locale negotiator'), - required=True, - ) - -def localenegotiator(_context, negotiator): - config = Configurator.with_context(_context) - config.set_locale_negotiator(negotiator) - -class IAdapterDirective(Interface): - """ - Register an adapter - """ - - factory = Tokens( - title=u"Adapter factory/factories", - description=(u"A list of factories (usually just one) that create" - " the adapter instance."), - required=True, - value_type=GlobalObject() - ) - - provides = GlobalInterface( - title=u"Interface the component provides", - description=(u"This attribute specifies the interface the adapter" - " instance must provide."), - required=False, - ) - - for_ = Tokens( - title=u"Specifications to be adapted", - description=u"This should be a list of interfaces or classes", - required=False, - value_type=GlobalObject( - missing_value=object(), - ), - ) - - name = TextLine( - title=u"Name", - description=(u"Adapters can have names.\n\n" - "This attribute allows you to specify the name for" - " this adapter."), - required=False, - ) - -def adapter(_context, factory, provides=None, for_=None, name=''): - if for_ is None: - if len(factory) == 1: - for_ = getattr(factory[0], '__component_adapts__', None) - - if for_ is None: - raise TypeError("No for argument was provided and can't " - "determine what the factory adapts.") - - for_ = tuple(for_) - - if provides is None: - if len(factory) == 1: - p = list(implementedBy(factory[0])) - if len(p) == 1: - provides = p[0] - - if provides is None: - raise TypeError("Missing 'provided' argument") - - # Generate a single factory from multiple factories: - factories = factory - if len(factories) == 1: - factory = factories[0] - elif len(factories) < 1: - raise ValueError("No factory specified") - elif len(factories) > 1 and len(for_) != 1: - raise ValueError("Can't use multiple factories and multiple " - "for") - else: - factory = _rolledUpFactory(factories) - - try: - registry = _context.registry - except AttributeError: # pragma: no cover (b/c) - registry = get_current_registry() - - _context.action( - discriminator = ('adapter', for_, provides, name), - callable = registry.registerAdapter, - args = (factory, for_, provides, name, _context.info), - ) - -class ISubscriberDirective(Interface): - """ - Register a subscriber - """ - - factory = GlobalObject( - title=u"Subscriber factory", - description=u"A factory used to create the subscriber instance.", - required=False, - ) - - handler = GlobalObject( - title=u"Handler", - description=u"A callable object that handles events.", - required=False, - ) - - provides = GlobalInterface( - title=u"Interface the component provides", - description=(u"This attribute specifies the interface the adapter" - " instance must provide."), - required=False, - ) - - for_ = Tokens( - title=u"Interfaces or classes that this subscriber depends on", - description=u"This should be a list of interfaces or classes", - required=False, - value_type=GlobalObject( - missing_value = object(), - ), - ) - -def subscriber(_context, for_=None, factory=None, handler=None, provides=None): - if factory is None: - if handler is None: - raise TypeError("No factory or handler provided") - if provides is not None: - raise TypeError("Cannot use handler with provides") - factory = handler - else: - if handler is not None: - raise TypeError("Cannot use handler with factory") - if provides is None: - raise TypeError( - "You must specify a provided interface when registering " - "a factory") - - if for_ is None: - for_ = getattr(factory, '__component_adapts__', None) - if for_ is None: - raise TypeError("No for attribute was provided and can't " - "determine what the factory (or handler) adapts.") - - for_ = tuple(for_) - - config = Configurator.with_context(_context) - - if handler is not None: - config.add_subscriber(handler, for_) - else: - registry = _context.registry - _context.action( - discriminator = None, - callable = registry.registerSubscriptionAdapter, - args = (factory, for_, provides, None, _context.info), - ) - -class IUtilityDirective(Interface): - """Register a utility.""" - - component = GlobalObject( - title=u"Component to use", - description=(u"Python name of the implementation object. This" - " must identify an object in a module using the" - " full dotted name. If specified, the" - " ``factory`` field must be left blank."), - required=False, - ) - - factory = GlobalObject( - title=u"Factory", - description=(u"Python name of a factory which can create the" - " implementation object. This must identify an" - " object in a module using the full dotted name." - " If specified, the ``component`` field must" - " be left blank."), - required=False, - ) - - provides = GlobalInterface( - title=u"Provided interface", - description=u"Interface provided by the utility.", - required=False, - ) - - name = TextLine( - title=u"Name", - description=(u"Name of the registration. This is used by" - " application code when locating a utility."), - required=False, - ) - -def utility(_context, provides=None, component=None, factory=None, name=''): - if factory and component: - raise TypeError("Can't specify factory and component.") - - if provides is None: - if factory: - provides = list(implementedBy(factory)) - else: - provides = list(providedBy(component)) - if len(provides) == 1: - provides = provides[0] - else: - raise TypeError("Missing 'provides' attribute") - - if factory: - kw = dict(factory=factory) - else: - # older component registries don't accept factory as a kwarg, - # so if we don't need it, we don't pass it - kw = {} - - try: - registry = _context.registry - except AttributeError: # pragma: no cover (b/c) - registry = get_current_registry() - - _context.action( - discriminator = ('utility', provides, name), - callable = registry.registerUtility, - args = (component, provides, name, _context.info), - kw = kw, - ) - -class IDefaultPermissionDirective(Interface): - name = TextLine(title=u'name', required=True) - -def default_permission(_context, name): - """ Register a default permission name """ - # the default permission must be registered eagerly so it can - # be found by the view registration machinery - config = Configurator.with_context(_context) - config.set_default_permission(name) - -def path_spec(context, path): - # we prefer registering asset specifications over absolute - # paths because these can be overridden by the asset directive. - if ':' in path and not os.path.isabs(path): - # it's already an asset specification - return path - abspath = context.path(path) - if hasattr(context, 'package') and context.package: - return asset_spec_from_abspath(abspath, context.package) - return abspath - -def zcml_configure(name, package): - """ Given a ZCML filename as ``name`` and a Python package as - ``package`` which the filename should be relative to, load the - ZCML into the current ZCML registry. - - """ - registry = get_current_registry() - configurator = Configurator(registry=registry, package=package) - configurator.load_zcml(name) - actions = configurator._ctx.actions[:] - configurator.commit() - return actions - -file_configure = zcml_configure # backwards compat (>0.8.1) - -deprecated( - 'zcml_configure', - '(pyramid.zcml.zcml_configure is deprecated as of Pyramid 1.0. Use' - '``pyramid.config.Configurator.load_zcml`` instead.) ') - -deprecated( - 'file_configure', - '(pyramid.zcml.file_configure is deprecated as of Pyramid 1.0. Use' - '``pyramid.config.Configurator.load_zcml`` instead.) ') - -def _rolledUpFactory(factories): - def factory(ob): - for f in factories: - ob = f(ob) - return ob - # Store the original factory for documentation - factory.factory = factories[0] - return factory - |
