pyramid_zcml¶
Overview¶
pyramid_zcml
is a package which provides ZCML directives for all
built-in Pyramid configurator methods.
Setup¶
Once pyramid_zcml
is installed, you must use the config.include
mechanism to include it into your Pyramid project’s configuration. In your
Pyramid project’s __init__.py
:
1 2 3 4 | import pyramid_zcml
config = Configurator(.....)
config.include(pyramid_zcml)
|
Do this before trying to load any ZCML. After this step is taken, it will be
possible to use the pyramid_zcml.load_zcml()
function as a method of
the configurator, ala:
1 | config.load_zcml(....)
|
Paster Template¶
The pyramid_starter_zcml
Paster template is included with this package.
You can use it via paster create -t pyramid_starter_zcml
(on Pyramid 1.0,
1.1, or 1.2) or pcreate -s pyramid_starter_zcml
(on Pyramid 1.3). It
creates a package skeleton which configures a Pyramid appliction via ZCML.
The application performs URL mapping via traversal and no persistence
mechanism.
Usage¶
Declarative Configuration using ZCML¶
The mode of configuration detailed in the examples within the Pyramid
documentation 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 For
Pyramid within pyramid_zcml
named ZCML which is declarative.
In ZCML, configuration statements are made via an domain specific language
implemented in XML. There is no opportunity for conditionals or loops.
Declarative languages are less powerful than their imperative counterparts;
this is attractive in environments where consistency is more important than
brevity.
A complete listing of ZCML directives is available within 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.
ZCML Configuration¶
A 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 ZCML (Zope Configuration Markup Language), an XML dialect.
A Pyramid application configured declaratively requires not one, but two files: a Python file and a ZCML file.
In a file named helloworld.py
:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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.include('pyramid_zcml')
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
:
1 2 3 4 5 6 7 8 9 | <configure xmlns="http://pylonshq.com/pyramid">
<include package="pyramid_zcml" />
<view
view="helloworld.hello_world"
/>
</configure>
|
This pair of files forms an application functionally equivalent to the application we created earlier in Imperative Configuration. Let’s examine the differences between that code listing and the code above.
In Imperative Configuration, we had the following lines within
the if __name__ == '__main__'
section of helloworld.py
:
1 2 3 4 5 | 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 pyramid_zcml.load_zcml()
method so that
it now reads as:
1 2 3 4 5 6 | if __name__ == '__main__':
config = Configurator()
config.include('pyramid_zcml')
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.include('pyramid_zcml')
line makes the load_zcml
method
available on the configurator. 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:
1 2 3 4 5 6 7 8 9 | <configure xmlns="http://pylonshq.com/pyramid">
<include package="pyramid_zcml" />
<view
view="helloworld.hello_world"
/>
</configure>
|
Note that this file contains some XML, and that the XML contains a
<view>
configuration declaration tag that references a
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
Imperative Configuration. In fact, the <view>
tag is
effectively a “macro” which calls the
pyramid.config.Configurator.add_view()
method on your
behalf.
The <view>
tag is an example of a Pyramid declaration
tag. Other such tags include <route>
and <scan>
. Each of
these tags is effectively a “macro” which calls methods of a
pyramid.config.Configurator
object on your behalf.
Essentially, using a 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 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 ZCML.
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <configure xmlns="http://pylonshq.com/pyramid">
<include package="pyramid_zcml" />
<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.
Hello World, Goodbye World (Declarative)¶
Another almost entirely equivalent mode of application configuration exists named declarative configuration. Pyramid can be configured for the same “hello world” application “declaratively”, if so desired.
To do so, first, create a file named helloworld.py
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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.include('pyramid_zcml')
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
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <configure xmlns="http://pylonshq.com/pyramid">
<include package="pyramid_zcml" />
<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 Hello World. We can run it the same way.
$ 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 Application Configuration, we had the following lines
within the if __name__ == '__main__'
section of helloworld.py
:
1 2 3 4 5 6 | 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
pyramid_zcml.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:
1 2 3 4 5 6 | if __name__ == '__main__':
config = Configurator()
config.include('pyramid_zcml')
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <configure xmlns="http://pylonshq.com/pyramid">
<include package="pyramid_zcml" />
<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 Hello World, but use of ZCML is new. Let’s break that down tag-by-tag.
The <configure>
Tag¶
The configure.zcml
ZCML file contains this bit of XML:
1 2 3 4 5 | <configure xmlns="http://pylonshq.com/pyramid">
<!-- other directives -->
</configure>
|
Because ZCML is XML, and because XML requires a single root
tag for each document, every ZCML file used by 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 configure and A Word On XML Namespaces.
The <include>
Tag¶
The configure.zcml
ZCML file contains this bit of XML within the
<configure>
root tag:
1 | <include package="pyramid_zcml" />
|
This self-closing tag instructs Pyramid to load a ZCML file
from the Python package with the dotted Python name
pyramid_zcml
, 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
pyramid_zcml
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:
1 2 | <include package="pyramid_zcml"
file="configure.zcml"/>
|
The <include>
tag that includes the ZCML statements implied by the
configure.zcml
file from the Python package named
pyramid_zcml
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_zcml"/>
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 include.
The <view>
Tag¶
The configure.zcml
ZCML file contains these bits of XML after the
<include>
tag, but within the <configure>
root tag:
1 2 3 4 5 6 7 8 | <view
view="helloworld.hello_world"
/>
<view
name="goodbye"
view="helloworld.goodbye_world"
/>
|
These <view>
declaration tags direct Pyramid to create
two view configuration registrations. The first <view>
tag has an attribute (the attribute is also named view
), which
points at a 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
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:
1 2 | config.add_view(hello_world)
config.add_view(goodbye_world, name='goodbye')
|
Each <view>
declaration tag encountered in a ZCML file effectively
invokes the pyramid.config.Configurator.add_view()
method on the behalf of the developer. Various attributes can be
specified on the <view>
tag which influence the view
configuration it creates.
Since the relative ordering of calls to
pyramid.config.Configurator.add_view()
doesn’t matter
(see the sidebar entitled View Dispatch and Ordering within
Adding Configuration), the relative order of <view>
tags in
ZCML doesn’t matter either. The following ZCML orderings are
completely equivalent:
Hello Before Goodbye
1 2 3 4 5 6 7 8 | <view
view="helloworld.hello_world"
/>
<view
name="goodbye"
view="helloworld.goodbye_world"
/>
|
Goodbye Before Hello
1 2 3 4 5 6 7 8 | <view
name="goodbye"
view="helloworld.goodbye_world"
/>
<view
view="helloworld.hello_world"
/>
|
We’ve now configured a Pyramid helloworld application declaratively. More information about this mode of configuration is available in ZCML Configuration.
ZCML Granularity¶
It’s extremely helpful to third party application “extenders” (aka
“integrators”) if the 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 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
.
Scanning via ZCML¶
ZCML can invoke a 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # 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.include('pyramid_zcml')
config.load_zcml('configure.zcml')
app = config.make_wsgi_app()
serve(app, host='0.0.0.0')
|
1 2 3 4 5 6 7 8 | <configure xmlns="http://pylonshq.com/pyramid">
<!-- configure.zcml -->
<include package="pyramid_zcml"/>
<scan package="."/>
</configure>
|
See also scan.
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.
Declarative configuraton was the more traditional form of configuration used in Pyramid applications; the first releases of Pyramid and all releases of Pyramid’s predecessor named repoze.bfg included ZCML in the core. However, by virtue of this package, it has been externalized from the Pyramid core because it has proven that imperative mode configuration can be simpler to understand and document.
However, you can choose to use imperative configuration, or declarative configuration via ZCML. Use the mode that best fits your brain as necessary.
View Configuration Via ZCML¶
You may associate a view with a URL by adding view
declarations via ZCML in a configure.zcml
file. An
example of a view declaration in ZCML is as follows:
1 2 3 4 5 | <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 resource location results:
- A context object which is an instance (or subclass) of the
Python class represented by
.resources.Hello
- A 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 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 resource type:
1 2 3 4 | <view
context=".resources.Hello"
view=".views.hello_world"
/>
|
A default view callable simply has no name
attribute. For the above
registration, when a context is found that is of the type
.resources.Hello
and there is no view name associated with the
result of 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:
1 2 3 4 5 | <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:
1 2 3 4 5 | <view
context="*"
view=".views.hello_world"
name="hello.html"
/>
|
This indicates that when Pyramid identifies that the
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 Defining a View Callable as a Class
apply for the class which is named.
See view for complete ZCML directive documentation.
Configuring a Route via ZCML¶
Instead of using the imperative pyramid.config.Configurator.add_route()
method to add a new route, you can alternately use ZCML.
route statements in a ZCML file. For example, the
following ZCML declaration causes a route to be added to the
application.
1 2 3 4 5 | <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
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 route for full route
ZCML directive
documentation.
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 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 Pyramid application using an
absolute path.
1 2 3 4 | <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
asset specification.
1 2 3 4 | <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.
1 2 3 4 | <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
pyramid.url.static_url()
.
For example, the static
ZCML directive may be fed a name
argument which is http://example.com/images
:
1 2 3 4 | <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
pyramid.url.static_url()
with paths that start with the path
argument passed to 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 pyramid.url.static_url()
API is discussed in more
detail later in this chapter.
The 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 Serving Static Assets for
more information.
The asset
ZCML Directive¶
Instead of using pyramid.config.Configurator.override_asset()
during
imperative configuration, an equivalent ZCML directive can be used.
The ZCML asset
tag is a frontend to using
pyramid.config.Configurator.override_asset()
.
An individual Pyramid asset
ZCML statement can override a
single asset. For example:
1 2 3 4 | <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:
1 2 3 4 | <asset
to_override="some.package"
override_with="another.package"
/>
|
Individual subdirectories within a package can also be overridden:
1 2 3 4 | <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:
1 2 3 4 | <asset
to_override=".subpackage:templates/"
override_with="another.package:templates/"
/>
|
See also asset.
Enabling an Authorization Policy Via ZCML¶
If you’d rather use 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 principal against the principals present in any ACL
found in the resource tree when attempting to call some view, modify
your configure.zcml
to look something like this:
1 2 3 4 5 6 7 8 9 10 | <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
pyramid.authentication.AuthTktAuthenticationPolicy
to be
injected as the authentication policy used by this application
and an instance of the class
pyramid.authorization.ACLAuthorizationPolicy
to be
injected as the authorization policy used by this application.
Pyramid ships with a number of authorization and authentication policy ZCML directives that should prove useful. See Built-In Authentication Policy ZCML Directives and Built-In Authorization Policy ZCML Directives for more information.
Built-In Authentication Policy ZCML Directives¶
Instead of configuring an authentication policy and authorization policy imperatively, 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:
1 2 3 4 5 6 7 8 9 10 11 12 | <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 authtktauthenticationpolicy 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:
1 2 3 4 | <remoteuserauthenticationpolicy
environ_key="REMOTE_USER"
callback=".somemodule.somefunc"
/>
|
See remoteuserauthenticationpolicy 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 repoze.who middleware.
An example of its usage, with all attributes fully expanded:
1 2 3 4 | <repozewho1authenticationpolicy
identifier_name="auth_tkt"
callback=".somemodule.somefunc"
/>
|
See repozewho1authenticationpolicy for detailed information.
Built-In Authorization Policy ZCML Directives¶
aclauthorizationpolicy
When this directive is used, authorization information is obtained from ACL objects attached to resources.
An example of its usage, with all attributes fully expanded:
1 | <aclauthorizationpolicy/>
|
In other words, it has no configuration attributes; its existence in a
configure.zcml
file enables it.
See aclauthorizationpolicy for detailed information.
Adding and Changing Renderers via ZCML¶
New templating systems and serializers can be associated with Pyramid renderer names. To this end, configuration declarations can be made which change an existing renderer factory and which add a new renderer factory.
Adding or changing an existing renderer via ZCML is accomplished via the renderer ZCML directive.
For example, to add a renderer which renders views which have a
renderer
attribute that is a path that ends in .jinja2
:
1 2 3 4 | <renderer
name=".jinja2"
factory="my.package.MyJinja2Renderer"
/>
|
The factory
attribute is a dotted Python name that must
point to an implementation of a renderer factory.
The name
attribute is the renderer name.
Registering a Renderer Factory¶
See Adding a New Renderer for more information for the definition of a renderer factory. Here’s an example of the registration of a simple renderer factory via ZCML:
1 2 3 4 | <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 view configuration:
1 2 3 4 | <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:
1 2 3 4 | <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 view
configuration:
1 2 3 4 | <view
view="mypackage.views.my_view"
renderer="templates/mytemplate.jinja2"
/>
|
When a 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 renderer and
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:
1 2 3 4 | <renderer
name=".zpt"
factory="pyramid.chameleon_zpt.renderer_factory"
/>
|
After you do this, 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:
1 2 3 4 | <renderer
name=".pt"
factory="my.package.pt_renderer"
/>
|
After you do this, the 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:
1 2 3 4 | <renderer
name=".txt"
factory="my.package.text_renderer"
/>
|
After you do this, the 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):
1 2 3 | <renderer
factory="pyramid.renderers.json_renderer_factory"
/>
|
See also renderer and
pyramid.config.Configurator.add_renderer()
.
Adding a Translation Directory via ZCML¶
You can add a translation directory via ZCML by using the translationdir ZCML directive:
1 | <translationdir dir="my.application:locale/"/>
|
A message catalog in a translation directory added via translationdir will be merged into translations from a message catalog added earlier if both translation directories contain translations for the same locale and translation domain.
See also translationdir and Adding a Translation Directory.
Adding a Custom Locale Negotiator via ZCML¶
You can add a custom locale negotiator via ZCML by using the localenegotiator ZCML directive:
1 2 3 | <localenegotiator
negotiator="my_application.my_module.my_locale_negotiator"
/>
|
See also Using a Custom Locale Negotiator and localenegotiator.
Configuring an Event Listener via ZCML¶
You can configure an 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:
1 2 3 4 | <subscriber
for="pyramid.events.NewRequest"
handler=".subscribers.mysubscriber"
/>
|
See also subscriber and Using Events.
Configuring a Not Found View via ZCML¶
If your application uses ZCML, you can replace the Not Found view by
placing something like the following ZCML in your configure.zcml
file.
1 2 3 4 | <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 Changing the Not Found View for more information.
Configuring a Forbidden View via ZCML¶
If your application uses ZCML, you can replace the Forbidden view by
placing something like the following ZCML in your configure.zcml
file.
1 2 3 4 | <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 Changing the Forbidden View for more information.
Configuring an Alternate Traverser via ZCML¶
Use an adapter
stanza in your application’s configure.zcml
to
change the default traverser:
1 2 3 4 5 | <adapter
factory="myapp.traversal.Traverser"
provides="pyramid.interfaces.ITraverser"
for="*"
/>
|
Or to register a traverser for a specific resource type:
1 2 3 4 5 | <adapter
factory="myapp.traversal.Traverser"
provides="pyramid.interfaces.ITraverser"
for="myapp.resources.MyRoot"
/>
|
See Changing the Traverser for more information.
Using features to make ZCML configurable¶
Using features you can make ZCML somewhat configurable. That is, you
can exclude or include parts of a ZCML configuration using the
features
argument to pyramid_zcml.load_zcml()
. For example:
1 | config.load_zcml('configure.zcml', features=['my_feature'])
|
With this ZCML file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <configure
xmlns="http://pylonshq.com/pyramid"
xmlns:zcml="http://namespaces.zope.org/zcml"
>
<include package="pyramid_zcml" />
<view
view="helloworld.always_configured"
/>
<view
zcml:condition="not-have my_feature"
view="helloworld.hello_world"
/>
<view
zcml:condition="have my_feature"
view="helloworld.alternate_hello_world"
/>
</configure>
|
Will configure the views always_configured
and alternate_hello_world
but NOT hello_world
.
Changing resource_url
URL Generation via ZCML¶
You can change how pyramid.url.resource_url()
generates a URL for a
specific type of resource by adding an adapter statement to your
configure.zcml
.
1 2 3 4 5 | <adapter
factory="myapp.traversal.URLGenerator"
provides="pyramid.interfaces.IContextURL"
for="myapp.resources.MyRoot *"
/>
|
See Changing How pyramid.request.Request.resource_url() Generates a URL for more information.
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
.
1 2 3 4 | <utility
component="mypackage.mymodule.MyRequest"
provides="pyramid.interfaces.IRequestFactory"
/>
|
See Changing the Request Factory for more information.
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
.
1 2 3 4 | <utility
component="mypackage.mymodule.renderer_globals_factory"
provides="pyramid.interfaces.IRendererGlobalsFactory"
/>
|
See adding_renderer_globals for more information.
Using Broken ZCML Directives¶
Some Zope and third-party ZCML directives use the
zope.component.getGlobalSiteManager
API to get “the registry” when
they should actually be calling zope.component.getSiteManager
.
zope.component.getSiteManager
can be overridden by Pyramid via
pyramid.config.Configurator.hook_zca()
, while
zope.component.getGlobalSiteManager
cannot. Directives that use
zope.component.getGlobalSiteManager
are effectively broken; no ZCML
directive should be using this function to find a registry to populate.
You cannot use ZCML directives which use
zope.component.getGlobalSiteManager
within a Pyramid application without
passing the ZCA global registry to the Configurator constructor at
application startup, as per Enabling the ZCA global API by using the ZCA global registry.
One alternative exists: fix the ZCML directive to use
getSiteManager
rather than getGlobalSiteManager
. If a
directive disuses getGlobalSiteManager
, the hook_zca
method of
using a component registry as documented in Enabling the ZCA global API by using hook_zca will begin
to work, allowing you to make use of the ZCML directive without
also using the ZCA global registry.
Directives and API¶
ZCML Directives¶
Comprehensive reference material for every ZCML directive provided by Pyramid is available within this chapter. The ZCML directive documentation is organized alphabetically by directive name.
aclauthorizationpolicy
¶
When this directive is used, authorization information is obtained from ACL objects attached to resource objects.
Attributes¶
None.
Example¶
1 | <aclauthorizationpolicy/>
|
Alternatives¶
You may create an instance of the
pyramid.authorization.ACLAuthorizationPolicy
and pass it
to the pyramid.config.Configurator
constructor as
the authorization_policy
argument during initial application
configuration.
See Also¶
See also Built-In Authorization Policy ZCML Directives and Security.
adapter
¶
Register a Zope Component Architecture “adapter”.
Attributes¶
factory
- The adapter factory (often a class).
provides
- The interface that an adapter instance resulting from a lookup will provide.
for
- Interfaces or classes to be adapted, separated by spaces,
e.g.
interfaces.IFoo interfaces.IBar
. name
- The adapter name.
Example¶
1 2 3 4 5 | <adapter
for=".foo.IFoo .bar.IBar"
provides=".interfaces.IMyAdapter"
factory=".adapters.MyAdapter"
/>
|
Alternatives¶
Use the registerAdapter
method of the registry
attribute of a
Configurator instance during initial application setup.
See Also¶
None.
authtktauthenticationpolicy
¶
When this directive is used, authentication information is obtained
from an paste.auth.auth_tkt
cookie value, assumed to be set by
a custom login form.
Attributes¶
secret
- The
secret
is a string that will be used to sign the data stored by the cookie. It is required and has no default. callback
- The
callback
is a Python dotted name to a function passed the string representing the userid stored in the cookie and the request as positional arguments. The callback is expected to return None if the user represented by the string doesn’t exist or a sequence of group identifiers (possibly empty) if the user does exist. Ifcallback
is None, the userid will be assumed to exist with no groups. It defaults toNone
. cookie_name
- The
cookie_name
is the name used for the cookie that contains the user information. It defaults toauth_tkt
. secure
secure
is a boolean value. If it’s set to “true”, the cookie will only be sent back by the browser over a secure (HTTPS) connection. It defaults to “false”.include_ip
include_ip
is a boolean value. If it’s set to true, the requesting IP address is made part of the authentication data in the cookie; if the IP encoded in the cookie differs from the IP of the requesting user agent, the cookie is considered invalid. It defaults to “false”.timeout
timeout
is an integer value. It represents the maximum age in seconds which the auth_tkt ticket will be considered valid. Iftimeout
is specified, andreissue_time
is also specified,reissue_time
must be a smaller value thantimeout
. It defaults toNone
, meaning that the ticket will be considered valid forever.reissue_time
reissue_time
is an integer value. Ifreissue_time
is specified, when we encounter a cookie that is older than the reissue time (in seconds), but younger that thetimeout
, a new cookie will be issued. It defaults toNone
, meaning that authentication cookies are never reissued. A value of0
means reissue a cookie in the response to every request that requires authentication.max_age
max_age
is the maximum age of the auth_tkt cookie, in seconds. This differs fromtimeout
inasmuch astimeout
represents the lifetime of the ticket contained in the cookie, while this value represents the lifetime of the cookie itself. When this value is set, the cookie’sMax-Age
andExpires
settings will be set, allowing the auth_tkt cookie to last between browser sessions. It is typically nonsensical to set this to a value that is lower thantimeout
orreissue_time
, although it is not explicitly prevented. It defaults toNone
, meaning (on all major browser platforms) that auth_tkt cookies will last for the lifetime of the user’s browser session.wild_domain
- A boolean value. If it’s set to “true”, a cookie with a “wild” domain
value will only be sent back by the browser during
remember
. It defaults to “true”.
Example¶
1 2 3 4 5 6 7 8 9 10 11 | <authtktauthenticationpolicy
secret="goshiamsosecret"
callback=".somemodule.somefunc"
cookie_name="mycookiename"
secure="false"
include_ip="false"
timeout="86400"
reissue_time="600"
max_age="31536000"
wild_domain="true"
/>
|
Alternatives¶
You may create an instance of the
pyramid.authentication.AuthTktAuthenticationPolicy
and
pass it to the pyramid.config.Configurator
constructor as the authentication_policy
argument during initial
application configuration.
asset
¶
The asset
directive adds an asset override for a single
static file/directory asset.
Attributes¶
to_override
- A asset specification specifying the asset to be overridden.
override_with
- A asset specification specifying the asset which is used as the override.
Examples¶
Overriding a Single Asset File
1 2 3 4 | <asset
to_override="some.package:templates/mytemplate.pt"
override_with="another.package:othertemplates/anothertemplate.pt"
/>
|
Overriding all Assets in a Package
1 2 3 4 | <asset
to_override="some.package"
override_with="another.package"
/>
|
Overriding all Assets in a Subdirectory of a Package
1 2 3 4 | <asset
to_override="some.package:templates/"
override_with="another.package:othertemplates/"
/>
|
Alternatives¶
The pyramid.config.Configurator.override_asset()
method can be used instead of the resource
ZCML directive.
This directive can also be invoked as the resource
ZCML directive for
backwards compatibility purposes.
See Also¶
See also The asset ZCML Directive.
configure
¶
Because ZCML is XML, and because XML requires a single root tag for
each document, every ZCML file used by 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.
Attributes¶
xmlns
- The default XML namespace used for subdirectives.
Example¶
1 2 3 4 5 | <configure xmlns="http://pylonshq.com/pyramid">
<!-- other directives -->
</configure>
|
A Word On XML Namespaces¶
Usually, the start tag of the <configure>
container tag has a
default XML namespace associated with it. This is usually
http://pylonshq.com/pyramid
, named by the xmlns
attribute of
the configure
start tag.
Using the http://pylonshq.com/pyramid
namespace as the default XML
namespace isn’t strictly necessary; you can use a different default namespace
as the default. However, if you do, the declaration tags which are defined
by Pyramid such as the view
declaration tag will need to be defined in
such a way that the XML parser that Pyramid uses knows which namespace the
pyramid
tags are associated with. For example, the following files
are all completely equivalent:
Use of A Non-Default XML Namespace
1 2 3 4 5 6 7 8 9 10 | <configure xmlns="http://namespaces.zope.org/zope"
xmlns:pyramid="http://pylonshq.com/pyramid">
<include package="pyramid.includes" />
<pyramid:view
view="helloworld.hello_world"
/>
</configure>
|
Use of A Per-Tag XML Namespace Without A Default XML Namespace
1 2 3 4 5 6 7 8 9 | <configure>
<include package="pyramid.includes" />
<view xmlns="http://pylonshq.com/pyramid"
view="helloworld.hello_world"
/>
</configure>
|
For more information about XML namespaces, see this older, but simple XML.com article.
The conventions in this document assume that the default XML namespace
is http://pylonshq.com/pyramid
.
Alternatives¶
None.
See Also¶
See also Hello World, Goodbye World (Declarative).
default_permission
¶
Set the default permission to be used by all view configuration registrations.
This directive accepts a single attribute ,``name``, which should be
used as the default permission string. An example of a permission
string: view
. Adding a default permission makes it unnecessary to
protect each view configuration with an explicit permission, unless
your application policy requires some exception for a particular view.
If a default permission is not set, views represented by view configuration registrations which do not explicitly declare a permission will be executable by entirely anonymous users (any authorization policy is ignored).
There can be only one default permission active at a time within an
application, thus the default_permission
directive can only be
used once in any particular set of ZCML.
Attributes¶
name
- Must be a string representing a permission,
e.g.
view
.
Example¶
1 2 3 | <default_permission
name="view"
/>
|
Alternatives¶
Using the default_permission
argument to the
pyramid.config.Configurator
constructor can be used
to achieve the same purpose.
Using the
pyramid.config.Configurator.set_default_permission()
method can be used to achieve the same purpose when using imperative
configuration.
See Also¶
See also Setting a Default Permission.
forbidden
¶
When Pyramid can’t authorize execution of a view based on the
authorization policy in use, it invokes a forbidden view.
The default forbidden response has a 401 status code and is very plain, but
it can be overridden as necessary using the forbidden
ZCML directive.
Warning
The forbidden
ZCML directive is deprecated in Pyramid
version 1.3. Instead, you should use the view
directive with a context
that names the
pyramid.exceptions.Forbidden
class. See
Changing the Forbidden View form more information.
Attributes¶
view
- The dotted Python name to a view callable. This
attribute is required unless a
renderer
attribute also exists. If arenderer
attribute exists on the directive, this attribute defaults to a view that returns an empty dictionary (see Writing View Callables Which Use a Renderer). attr
- The attribute of the view callable to use if
__call__
is not correct (has the same meaning as in the context of view; see the description ofattr
there). renderer
- This is either a single string term (e.g.
json
) or a string implying a path or asset specification (e.g.templates/views.pt
) used when the view returns a non-response object. This attribute has the same meaning as it would in the context of view; see the description ofrenderer
there). wrapper
- The view name (not an object dotted name) of another view
declared elsewhere in ZCML (or via the
@view_config
decorator) which will receive the response body of this view as therequest.wrapped_body
attribute of its own request, and the response returned by this view as therequest.wrapped_response
attribute of its own request. This attribute has the same meaning as it would in the context of view; see the description ofwrapper
there). Note that the wrapper view should not be protected by any permission; behavior is undefined if it does.
Example¶
1 2 | <forbidden
view="helloworld.views.forbidden_view"/>
|
Alternatives¶
Use the view directive with a context
that names
the pyramid.exceptions.Forbidden
class.
Use the pyramid.config.Configurator.add_view()
method,
passing it a context
which is the
pyramid.exceptions.Forbidden
class.
See Also¶
See also Changing the Forbidden View.
include
¶
The include
directive includes configuration from an external ZCML
file. Use of the include
tag allows a user to split configuration
across multiple ZCML files, and allows package distributors to provide
default ZCML configuration for specific purposes which can be
included by the integrator of the package as necessary.
Attributes¶
package
- A dotted Python name which references a Python package.
file
- An absolute or relative filename which references a ZCML file.
The package
and file
attributes can be used together or
separately as necessary.
Examples¶
Loading the File Named configure.zcml
from a Package Implicitly
1 | <include package="some.package" />
|
Loading the File Named other.zcml
From the Current Package
1 | <include file="other.zcml" />
|
Loading a File From a Subdirectory of the Current Package
1 | <include file="subdir/other.zcml" />
|
Loading the File Named /absolute/path/other.zcml
1 | <include file="/absolute/path/other.zcml" />
|
Loading the File Named other.zcml
From a Package Explicitly
1 | <include package="some.package" file="other.zcml" />
|
Alternatives¶
None.
See Also¶
See also Hello World, Goodbye World (Declarative).
localenegotiator
¶
Set the locale negotiator for the current configurator to support localization of text.
Attributes¶
negotiator
The dotted Python name to a locale negotiator implementation. This attribute is required. If it begins with a dot (.
), the name will be considered relative to the directory in which the ZCML file which contains this directive lives.
Example¶
1 2 3 | <localenegotiator
negotiator="some.package.module.my_locale_negotiator"
/>
|
Alternatives¶
Use pyramid.config.Configurator.set_locale_negotiator()
method instance during initial application setup.
See Also¶
See also Activating Translation.
notfound
¶
Warning
The notfound
ZCML directive is deprecated in Pyramid
version 1.0. Instead, you should use the view
directive with a context
that names the
pyramid.exceptions.NotFound
class. See
Changing the Not Found View form more information.
When Pyramid can’t map a URL to view code, it invokes a not found
view. The default not found view is very plain, but the view callable used
can be configured via the notfound
ZCML tag.
Attributes¶
view
- The dotted Python name to a view callable. This
attribute is required unless a
renderer
attribute also exists. If arenderer
attribute exists on the directive, this attribute defaults to a view that returns an empty dictionary (see Writing View Callables Which Use a Renderer). attr
- The attribute of the view callable to use if
__call__
is not correct (has the same meaning as in the context of view; see the description ofattr
there). renderer
- This is either a single string term (e.g.
json
) or a string implying a path or asset specification (e.g.templates/views.pt
) used when the view returns a non-response object. This attribute has the same meaning as it would in the context of view; see the description ofrenderer
there). wrapper
- The view name (not an object dotted name) of another view
declared elsewhere in ZCML (or via the
@view_config
decorator) which will receive the response body of this view as therequest.wrapped_body
attribute of its own request, and the response returned by this view as therequest.wrapped_response
attribute of its own request. This attribute has the same meaning as it would in the context of view; see the description ofwrapper
there). Note that the wrapper view should not be protected by any permission; behavior is undefined if it does.
Example¶
1 2 | <notfound
view="helloworld.views.notfound_view"/>
|
Alternatives¶
Use the view directive with a context
that names
the pyramid.exceptions.NotFound
class.
Use the pyramid.config.Configurator.add_view()
method,
passing it a context
which is the
pyramid.exceptions.NotFound
class.
See Also¶
See also Changing the Not Found View.
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.
Attributes¶
environ_key
- The
environ_key
is the name that will be used to obtain the remote user value from the WSGI environment. It defaults toREMOTE_USER
. callback
- The
callback
is a Python dotted name to a function passed the string representing the remote user and the request as positional arguments. The callback is expected to return None if the user represented by the string doesn’t exist or a sequence of group identifiers (possibly empty) if the user does exist. Ifcallback
is None, the userid will be assumed to exist with no groups. It defaults toNone
.
Example¶
1 2 3 4 | <remoteuserauthenticationpolicy
environ_key="REMOTE_USER"
callback=".somemodule.somefunc"
/>
|
Alternatives¶
You may create an instance of the
pyramid.authentication.RemoteUserAuthenticationPolicy
and
pass it to the pyramid.config.Configurator
constructor as the authentication_policy
argument during initial
application configuration.
renderer
¶
The renderer
ZCML directive can be used to override an existing
existing renderer or to add a new renderer.
Attributes¶
factory
- A dotted Python name referencing a callable object that accepts a renderer name and returns a renderer object.
name
- The renderer name, which is a string.
Examples¶
Registering a Non-Template Renderer
1 2 3 4 | <renderer
factory="some.renderer"
name="mynewrenderer"
/>
|
Registering a Template Renderer
1 2 3 4 | <renderer
factory="some.jinja2.renderer"
name=".jinja2"
/>
|
Alternatives¶
The pyramid.config.Configurator.add_renderer()
method
is equivalent to the renderer
ZCML directive.
See Also¶
See also Adding and Changing Renderers.
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 repoze.who middleware.
Attributes¶
identifier_name
- The
identifier_name
controls the name used to look up the repoze.who “identifier” plugin withinrequest.environ['repoze.who.plugins']
which is used by this policy to “remember” and “forget” credentials. It defaults toauth_tkt
. callback
- The
callback
is a Python dotted name to a function passed the repoze.who identity and the request as positional arguments. The callback is expected to return None if the user represented by the identity doesn’t exist or a sequence of group identifiers (possibly empty) if the user does exist. Ifcallback
is None, the userid will be assumed to exist with no groups. It defaults toNone
.
Example¶
1 2 3 4 | <repozewho1authenticationpolicy
identifier_name="auth_tkt"
callback=".somemodule.somefunc"
/>
|
Alternatives¶
You may create an instance of the
pyramid.authentication.RepozeWho1AuthenticationPolicy
and
pass it to the pyramid.config.Configurator
constructor as the authentication_policy
argument during initial
application configuration.
route
¶
The route
directive adds a single route configuration to
the application registry.
Attributes¶
pattern
The pattern of the route e.g.
ideas/{idea}
. This attribute is required. See Route Pattern Syntax for information about the syntax of route patterns.Note
For backwards compatibility purposes, the
path
attribute can also be used instead ofpattern
.name
- The name of the route, e.g.
myroute
. This attribute is required. It must be unique among all defined routes in a given configuration. factory
- The dotted Python name to a function that will generate a
Pyramid context object when this route matches.
e.g.
mypackage.resources.MyResource
. If this argument is not specified, a default root factory will be used. view
- The dotted Python name to a function that will be used as a
view callable when this route matches.
e.g.
mypackage.views.my_view
. xhr
- This value should be either
True
orFalse
. If this value is specified and isTrue
, the request must possess anHTTP_X_REQUESTED_WITH
(akaX-Requested-With
) header for this route to match. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries. If this predicate returns false, route matching continues. traverse
If you would like to cause the context to be something other than the root object when this route matches, you can spell a traversal pattern as the
traverse
argument. This traversal pattern will be used as the traversal path: traversal will begin at the root object implied by this route (either the global root, or the object returned by thefactory
associated with this route).The syntax of the
traverse
argument is the same as it is forpattern
. For example, if thepattern
provided to theroute
directive isarticles/{article}/edit
, and thetraverse
argument provided to theroute
directive is/{article}
, when a request comes in that causes the route to match in such a way that thearticle
match value is ‘1’ (when the request URI is/articles/1/edit
), the traversal path will be generated as/1
. This means that the root object’s__getitem__
will be called with the name1
during the traversal phase. If the1
object exists, it will become the context of the request. Traversal has more information about traversal.If the traversal path contains segment marker names which are not present in the
pattern
argument, a runtime error will occur. Thetraverse
pattern should not contain segment markers that do not exist in thepattern
.A similar combining of routing and traversal is available when a route is matched which contains a
*traverse
remainder marker in itspattern
(see Using *traverse in a Route Pattern). Thetraverse
argument to theroute
directive allows you to associate route patterns with an arbitrary traversal path without using a a*traverse
remainder marker; instead you can use other match information.Note that the
traverse
argument to theroute
directive is ignored when attached to a route that has a*traverse
remainder marker in its pattern.request_method
- A string representing an HTTP method name, e.g.
GET
,POST
,HEAD
,DELETE
,PUT
. If this argument is not specified, this route will match if the request has any request method. If this predicate returns false, route matching continues. path_info
- The value of this attribute represents a regular expression pattern
that will be tested against the
PATH_INFO
WSGI environment variable. If the regex matches, this predicate will be true. If this predicate returns false, route matching continues. request_param
- This value can be any string. A view declaration with this
attribute ensures that the associated route will only match when the
request has a key in the
request.params
dictionary (an HTTPGET
orPOST
variable) that has a name which matches the supplied value. If the value supplied to the attribute has a=
sign in it, e.g.request_params="foo=123"
, then the key (foo
) must both exist in therequest.params
dictionary, and the value must match the right hand side of the expression (123
) for the route to “match” the current request. If this predicate returns false, route matching continues. header
- The value of this attribute represents an HTTP header name or a
header name/value pair. If the value contains a
:
(colon), it will be considered a name/value pair (e.g.User-Agent:Mozilla/.*
orHost:localhost
). The value of an attribute that represent a name/value pair should be a regular expression. If the value does not contain a colon, the entire value will be considered to be the header name (e.g.If-Modified-Since
). If the value evaluates to a header name only without a value, the header specified by the name must be present in the request for this predicate to be true. If the value evaluates to a header name/value pair, the header specified by the name must be present in the request and the regular expression specified as the value must match the header value. Whether or not the value represents a header name or a header name/value pair, the case of the header name is not significant. If this predicate returns false, route matching continues. accept
- The value of this attribute represents a match query for one or more
mimetypes in the
Accept
HTTP request header. If this value is specified, it must be in one of the following forms: a mimetype match token in the formtext/plain
, a wildcard mimetype match token in the formtext/*
or a match-all wildcard mimetype match token in the form*/*
. If any of the forms matches theAccept
header of the request, this predicate will be true. If this predicate returns false, route matching continues.
custom_predicates
This value should be a sequence of references to custom predicate callables. Use custom predicates when no set of predefined predicates does what you need. Custom predicates can be combined with predefined predicates as necessary. Each custom predicate callable should accept two arguments:
info
andrequest
and should return eitherTrue
orFalse
after doing arbitrary evaluation of the info and/or the request. If all custom and non-custom predicate callables returnTrue
the associated route will be considered viable for a given request. If any predicate callable returnsFalse
, route matching continues. Note that the valueinfo
passed to a custom route predicate is a dictionary containing matching information; see Custom Route Predicates for more information aboutinfo
.Note
this argument is deprecated as of Pyramid 1.5.
view_context
The dotted Python name to a class or an interface that the context of the view should match for the view named by the route to be used. This attribute is only useful if the
view
attribute is used. If this attribute is not specified, the default (None
) will be used.If the
view
attribute is not provided, this attribute has no effect.This attribute can also be spelled as
view_for
orfor_
; these are valid older spellings.view_permission
The permission name required to invoke the view associated with this route. e.g.
edit
. (see Using Pyramid Security with URL Dispatch for more information about permissions).If the
view
attribute is not provided, this attribute has no effect.This attribute can also be spelled as
permission
.view_renderer
This is either a single string term (e.g.
json
) or a string implying a path or asset specification (e.g.templates/views.pt
). If the renderer value is a single term (does not contain a dot.
), the specified term will be used to look up a renderer implementation, and that renderer implementation will be used to construct a response from the view return value. If the renderer term contains a dot (.
), the specified term will be treated as a path, and the filename extension of the last element in the path will be used to look up the renderer implementation, which will be passed the full path. The renderer implementation will be used to construct a response from the view return value. See Writing View Callables Which Use a Renderer for more information.If the
view
attribute is not provided, this attribute has no effect.This attribute can also be spelled as
renderer
.view_attr
The view machinery defaults to using the
__call__
method of the view callable (or the function itself, if the view callable is a function) to obtain a response dictionary. Theattr
value allows you to vary the method attribute used to obtain the response. For example, if your view was a class, and the class has a method namedindex
and you wanted to use this method instead of the class’__call__
method to return the response, you’d sayattr="index"
in the view configuration for the view. This is most useful when the view definition is a class.If the
view
attribute is not provided, this attribute has no effect.use_global_views
- When a request matches this route, and view lookup cannot find a view which has a ‘route_name’ predicate argument that matches the route, try to fall back to using a view that otherwise matches the context, request, and view name (but does not match the route name predicate).
Alternatives¶
You can also add a route configuration via:
- Using the
pyramid.config.Configurator.add_route()
method.
See Also¶
See also URL Dispatch.
scan
¶
To make use of configuration decoration decorators, you must
perform a scan. A scan finds these decorators in code. The
scan
ZCML directive tells Pyramid to begin such a scan.
Attributes¶
package
- The package to scan or the single dot (
.
), meaning the “current” package (the package in which the ZCML file lives).
Example¶
1 | <scan package="."/>
|
Alternatives¶
The pyramid.config.Configurator.scan()
method performs
the same job as the scan
ZCML directive.
See Also¶
See also Adding View Configuration Using the @view_config Decorator.
static
¶
Use of the static
ZCML directive or allows you to serve static
resources (such as JavaScript and CSS files) within a
Pyramid application. This mechanism makes static files
available at a name relative to the application root URL.
Attributes¶
name
- The (application-root-relative) URL prefix of the static directory.
For example, to serve static files from
/static
in most applications, you would provide aname
ofstatic
. path
- A path to a directory on disk where the static files live. This
path may either be 1) absolute (e.g.
/foo/bar/baz
) 2) Python-package-relative (e.g. (packagename:foo/bar/baz
) or 3) relative to the package directory in which the ZCML file which contains the directive (e.g.foo/bar/baz
). cache_max_age
- The number of seconds that the static resource can be cached, as
represented in the returned response’s
Expires
and/orCache-Control
headers, when any static file is served from this directive. This defaults to 3600 (5 minutes). Optional. permission
- Used to specify the permission required by a user to execute
this static view. This value defaults to the string
__no_permission_required__
. The__no_permission_required__
string is a special sentinel which indicates that, even if a default permission exists for the current application, the static view should be renderered to completely anonymous users. This default value is permissive because, in most web apps, static resources seldom need protection from viewing. You should use this option only if you register a static view which points at a directory that contains resources which should be shown only if the calling user has (according to the authorization policy) a particular permission.
Examples¶
Serving Static Files from an Absolute Path
1 2 3 4 | <static
name="static"
path="/var/www/static"
/>
|
Serving Static Files from a Package-Relative Path
1 2 3 4 | <static
name="static"
path="some_package:a/b/c/static"
/>
|
Serving Static Files from a Current-Package-Relative Path
1 2 3 4 | <static
name="static"
path="static_files"
/>
|
Alternatives¶
pyramid.config.Configurator.add_static_view()
can also
be used to add a static view.
See Also¶
See also Serving Static Assets and Generating Static Asset URLs.
subscriber
¶
The subscriber
ZCML directive configures an subscriber
callable to listen for events broadcast by the Pyramid web
framework.
Attributes¶
for
- The class or interface that you are subscribing the listener for,
e.g.
pyramid.events.NewRequest
. Registering a subscriber for a specific class or interface limits the event types that the subscriber will receive to those specified by the interface or class. Default:zope.interface.Interface
(implying any event type). handler
- A dotted Python name which references an event handler
callable. The callable should accept a single argument:
event
. The return value of the callable is ignored.
Examples¶
1 2 3 4 | <subscriber
for="pyramid.events.NewRequest"
handler=".subscribers.handle_new_request"
/>
|
Alternatives¶
You can also register an event listener by using the
pyramid.config.Configurator.add_subscriber()
method.
See Also¶
See also Using Events.
translationdir
¶
Add a gettext translation directory to the current configuration for use in localization of text.
Attributes¶
dir
- The path to the translation directory. This path may either be 1)
absolute (e.g.
/foo/bar/baz
) 2) Python-package-relative (e.g.packagename:foo/bar/baz
) or 3) relative to the package directory in which the ZCML file which contains the directive (e.g.foo/bar/baz
).
Example 1¶
1 2 3 4 5 | <!-- relative to configure.zcml file -->
<translationdir
dir="locale"
/>
|
Example 2¶
1 2 3 4 5 | <!-- relative to another package -->
<translationdir
dir="another.package:locale"
/>
|
Example 3¶
1 2 3 4 5 | <!-- an absolute directory name -->
<translationdir
dir="/usr/share/locale"
/>
|
Alternatives¶
Use pyramid.config.Configurator.add_translation_dirs()
method instance during initial application setup.
See Also¶
See also Activating Translation.
utility
¶
Register a Zope Component Architecture “utility”.
Attributes¶
component
- The utility component (cannot be specified if
factory
is specified). factory
- A factory that creates a component (cannot be specified if
component
is specified). provides
- The interface that an utility instance resulting from a lookup will provide.
name
- The utility name.
Example¶
1 2 3 4 | <utility
provides=".interfaces.IMyUtility"
component=".utilities.MyUtility"
/>
|
Alternatives¶
Use the registerUtility
method of the registry
attribute of a
Configurator instance during initial application setup.
See Also¶
None.
view
¶
A view
declaration directs Pyramid to create a single
view configuration registration in the current
application registry.
The view
ZCML directive has many possible attributes. Some of the
attributes are descriptive or influence rendering. Other attributes
are predicate attributes, meaning that they imply an
evaluation to true or false when view lookup is performed.
All predicates named in a view configuration must evaluate to true in order for the view callable it names to be considered “invokable” for a given request. See View Configuration for a description of how a view configuration matches (or doesn’t match) during a request.
The possible attributes of the view
ZCML directive are described
below. They are divided into predicate and non-predicate categories.
Attributes¶
Non-Predicate Attributes¶
view
- The dotted Python name to a view callable. This
attribute is required unless a
renderer
attribute also exists. If arenderer
attribute exists on the directive, this attribute defaults to a view that returns an empty dictionary (see Writing View Callables Which Use a Renderer). permission
- The name of a permission that the user must possess in order to call the view. See Configuring View Security for more information about view security and permissions.
attr
- The view machinery defaults to using the
__call__
method of the view callable (or the function itself, if the view callable is a function) to obtain a response dictionary. Theattr
value allows you to vary the method attribute used to obtain the response. For example, if your view was a class, and the class has a method namedindex
and you wanted to use this method instead of the class’__call__
method to return the response, you’d sayattr="index"
in the view configuration for the view. This is most useful when the view definition is a class. renderer
This is either a single string term (e.g.
json
) or a string implying a path or asset specification (e.g.templates/views.pt
). If the renderer value is a single term (does not contain a dot.
), the specified term will be used to look up a renderer implementation, and that renderer implementation will be used to construct a response from the view return value. If the renderer term contains a dot (.
), the specified term will be treated as a path, and the filename extension of the last element in the path will be used to look up the renderer implementation, which will be passed the full path. The renderer implementation will be used to construct a response from the view return value.Note that if the view itself returns a response (see View Callable Responses), the specified renderer implementation is never called.
When the renderer is a path, although a path is usually just a simple relative pathname (e.g.
templates/foo.pt
, implying that a template named “foo.pt” is in the “templates” directory relative to the directory in which the ZCML file is defined), a path can be absolute, starting with a slash on UNIX or a drive letter prefix on Windows. The path can alternately be a asset specification in the formsome.dotted.package_name:relative/path
, making it possible to address template assets which live in a separate package.The
renderer
attribute is optional. If it is not defined, the “null” renderer is assumed (no rendering is performed and the value is passed back to the upstream BFG machinery unmolested).wrapper
- The view name (not an object dotted name) of another view
declared elsewhere in ZCML (or via the
@view_config
decorator) which will receive the response body of this view as therequest.wrapped_body
attribute of its own request, and the response returned by this view as therequest.wrapped_response
attribute of its own request. Using a wrapper makes it possible to “chain” views together to form a composite response. The response of the outermost wrapper view will be returned to the user. The wrapper view will be found as any view is found: see View Configuration. The “best” wrapper view will be found based on the lookup ordering: “under the hood” this wrapper view is looked up viapyramid.view.render_view_to_response(context, request, 'wrapper_viewname')
. The context and request of a wrapper view is the same context and request of the inner view. If this attribute is unspecified, no view wrapping is done.
Predicate Attributes¶
name
- The view name. Read the Traversal to understand the concept of a view name.
context
- A dotted Python name representing the Python class that the
context must be an instance of, or the interface
that the context must provide in order for this view to be
found and called. This predicate is true when the context
is an instance of the represented class or if the context
provides the represented interface; it is otherwise false. An
alternate name for this attribute is
for
(this is an older spelling). route_name
- This attribute services an advanced feature that isn’t often used
unless you want to perform traversal after a route has matched.
This value must match the
name
of a<route>
declaration (see URL Dispatch) that must match before this view will be called. Note that theroute
configuration referred to byroute_name
usually has a*traverse
token in the value of itspath
, representing a part of the path that will be used by traversal against the result of the route’s root factory. See Combining Traversal and URL Dispatch for more information on using this advanced feature. request_type
- This value should be a dotted Python name string representing the interface that the request must have in order for this view to be found and called. The presence of this attribute is largely for backwards compatibility with older iterations of this framework.
request_method
- This value can either be one of the strings ‘GET’, ‘POST’, ‘PUT’,
‘DELETE’, or ‘HEAD’ representing an HTTP
REQUEST_METHOD
. A view declaration with this attribute ensures that the view will only be called when the request’smethod
(akaREQUEST_METHOD
) string matches the supplied value. request_param
- This value can be any string. A view declaration with this
attribute ensures that the view will only be called when the request
has a key in the
request.params
dictionary (an HTTPGET
orPOST
variable) that has a name which matches the supplied value. If the value supplied to the attribute has a=
sign in it, e.g.request_params="foo=123"
, then the key (foo
) must both exist in therequest.params
dictionary, and the value must match the right hand side of the expression (123
) for the view to “match” the current request. containment
- This value should be a dotted Python name string representing the class that a graph traversal parent object of the context must be an instance of (or interface that a parent object must provide) in order for this view to be found and called. Your resources must be “location-aware” to use this feature. See Location-Aware Resources for more information about location-awareness.
xhr
- This value should be either
True
orFalse
. If this value is specified and isTrue
, the request must possess anHTTP_X_REQUESTED_WITH
(akaX-Requested-With
) header that has the valueXMLHttpRequest
for this view to be found and called. This is useful for detecting AJAX requests issued from jQuery, Prototype and other Javascript libraries. accept
- The value of this attribute represents a match query for one or more
mimetypes in the
Accept
HTTP request header. If this value is specified, it must be in one of the following forms: a mimetype match token in the formtext/plain
, a wildcard mimetype match token in the formtext/*
or a match-all wildcard mimetype match token in the form*/*
. If any of the forms matches theAccept
header of the request, this predicate will be true. header
- The value of this attribute represents an HTTP header name or a
header name/value pair. If the value contains a
:
(colon), it will be considered a name/value pair (e.g.User-Agent:Mozilla/.*
orHost:localhost
). The value of an attribute that represent a name/value pair should be a regular expression. If the value does not contain a colon, the entire value will be considered to be the header name (e.g.If-Modified-Since
). If the value evaluates to a header name only without a value, the header specified by the name must be present in the request for this predicate to be true. If the value evaluates to a header name/value pair, the header specified by the name must be present in the request and the regular expression specified as the value must match the header value. Whether or not the value represents a header name or a header name/value pair, the case of the header name is not significant. path_info
- The value of this attribute represents a regular expression pattern
that will be tested against the
PATH_INFO
WSGI environment variable. If the regex matches, this predicate will be true. custom_predicates
This value should be a sequence of references to custom predicate callables (e.g.
dotted.name.one dotted.name.two
, if used in ZCML; a dotted Python name to each callable separated by a space). Use custom predicates when no set of predefined predicates do what you need. Custom predicates can be combined with predefined predicates as necessary. Each custom predicate callable should accept two arguments:context
andrequest
and should return eitherTrue
orFalse
after doing arbitrary evaluation of the context and/or the request. If all callables returnTrue
, the associated view callable will be considered viable for a given request.Note
this argument is deprecated as of Pyramid 1.5.
decorator
- A dotted Python name to a function that will be used to decorate
the registered view callable. The decorator function will be
called with the view callable as a single argument. The view callable it
is passed will accept
(context, request)
. The decorator must return a replacement view callable which also accepts(context, request)
. mapper
- A dotted Python name which refers to a view mapper, or
None
. By default it isNone
, which indicates that the view should use the default view mapper. This plug-point is useful for Pyramid extension developers, but it’s not very useful for ‘civilians’ who are just developing stock Pyramid applications.
Examples¶
Registering A Default View for a Class
1 2 3 4 | <view
context=".resources.MyResource"
view=".views.hello_world"
/>
|
Registering A View With a Predicate
1 2 3 4 5 | <view
context=".resources.MyResource"
view=".views.hello_world_post"
request_method="POST"
/>
|
Alternatives¶
You can also add a view configuration via:
- Using the
pyramid.view.view_config
class as a decorator. - Using the
pyramid.config.Configurator.add_view()
method.
pyramid_zcml
API¶
-
pyramid_zcml.
load_zcml
(spec='configure.zcml', features=())¶ Load configuration from a ZCML file into the current configuration state. The
spec
argument is an absolute filename, a relative filename, or a asset specification, defaulting toconfigure.zcml
(relative to the package of the method’s caller).The
features
argument can be any iterable of strings. These are useful for conditionally including or excluding parts of a ZCML file.
-
pyramid_zcml.
make_app
(root_factory, package=None, filename='configure.zcml', settings=None)¶ Return a Router object, representing a fully configured Pyramid WSGI application.
Warning
Use of this function is deprecated as of Pyramid 1.0. You should instead use a
pyramid.config.Configurator
instance to perform startup configuration as shown in Application Configuration.root_factory
must be a callable that accepts a 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 beNone
, in which case a ‘default default’ traversal root is used.package
is a Python package or module representing the application’s package. It is optional, defaulting toNone
.package
may beNone
. Ifpackage
isNone
, thefilename
passed or the value in theoptions
dictionary namedconfigure_zcml
must be a) absolute pathname to a ZCML file that represents the application’s configuration or b) a asset specification to a ZCML file in the formdotted.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 toconfigure.zcml
. It can also be a ;term:asset specification in the formdotted_package_name:relative/file/path.zcml
. Note that if any value forconfigure_zcml
is passed within thesettings
dictionary, the value passed asfilename
will be ignored, replaced with theconfigure_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 parameteroptions
is a backwards compatibility alias for thesettings
keyword parameter.
-
pyramid_zcml.
includeme
(config)¶ Function meant to be included via
pyramid.config.Configurator.include()
, which sets up the Configurator with aload_zcml
method.
Glossary¶
- application registry
- A registry of configuration information consulted by Pyramid while servicing an application. An application registry maps resource types to views, as well as housing other application-specific component registrations. Every Pyramid application has one (and only one) application registry.
- asset
- Any file contained within a Python package which is not a Python source code file.
- asset specification
- A colon-delimited identifier for an asset. The colon separates
a Python package name from a package subpath. For example, the
asset specification
my.package:static/baz.css
identifies the file namedbaz.css
in thestatic
subdirectory of themy.package
Python package. See Understanding Asset Specifications for more info. - asset specification
- A colon-delimited identifier for an asset. The colon separates
a Python package name from a package subpath. For example, the
asset specification
my.package:static/baz.css
identifies the file namedbaz.css
in thestatic
subdirectory of themy.package
Python package. See Understanding Asset Specifications for more info. - authentication policy
- An authentication policy in Pyramid terms is a bit of code which has an API which determines the current principal (or principals) associated with a request.
- An authorization policy in Pyramid terms is a bit of code which has an API which determines whether or not the principals associated with the request can perform an action associated with a permission, based on the information found on the context resource.
- configuration declaration
- An individual method call made to an instance of a Pyramid
Configurator object which performs an arbitrary action, such as
registering a view configuration (via the
add_view
method of the configurator) or route configuration (via theadd_route
method of the configurator). - configuration decoration
- Metadata implying one or more configuration declaration
invocations. Often set by configuration Python decorator
attributes, such as
pyramid.view.view_config
, aka@view_config
. - configurator
- An object used to do configuration declaration within an
application. The most common configurator is an instance of the
pyramid.config.Configurator
class. - decorator
- A wrapper around a Python function or class which accepts the function or class as its first argument and which returns an arbitrary object. Pyramid provides several decorators, used for configuration and return value modification purposes. See also PEP 318.
- Default Locale Name
- The locale name used by an application when no explicit locale name is set. See Localization-Related Deployment Settings.
- default permission
- A permission which is registered as the default for an
entire application. When a default permission is in effect,
every view configuration registered with the system will
be effectively amended with a
permission
argument that will require that the executing user possess the default permission in order to successfully execute the associated view callable See also Setting a Default Permission. - Default view
- The default view of a resource is the view invoked when the
view name is the empty string (
''
). This is the case when traversal exhausts the path elements in the PATH_INFO of a request before it returns a context resource. - dotted Python name
- A reference to a Python object by name using a string, in the form
path.to.modulename:attributename
. Often used in Paste and setuptools configurations. A variant is used in dotted names within ZCML attributes that name objects (such as the ZCML “view” directive’s “view” attribute): the colon (:
) is not used; in its place is a dot. - Exception view
- An exception view is a view callable which may be invoked by Pyramid when an exception is raised during request processing. See Custom Exception Views for more information.
- Forbidden view
- An exception view invoked by Pyramid when the
developer explicitly raises a
pyramid.exceptions.Forbidden
exception from within view code or root factory code, or when the view configuration and authorization policy found for a request disallows a particular view invocation. Pyramid provides a default implementation of a forbidden view; it can be overridden. See Changing the Forbidden View. - imperative configuration
- The configuration mode in which you use Python to call methods on a Configurator in order to add each configuration declaration required by your application.
- Locale Name
- A string like
en
,en_US
,de
, orde_AT
which uniquely identifies a particular locale. - Locale Negotiator
- An object supplying a policy determining which locale
name best represents a given request. It is used by the
pyramid.i18n.get_locale_name()
, andpyramid.i18n.negotiate_locale_name()
functions, and indirectly bypyramid.i18n.get_localizer()
. Thepyramid.i18n.default_locale_negotiator()
function is an example of a locale negotiator. - module
- A Python source file; a file on the filesystem that typically ends with
the extension
.py
or.pyc
. Modules often live in a package. - Not Found view
- An exception view invoked by Pyramid when the
developer explicitly raises a
pyramid.exceptions.NotFound
exception from within view code or root factory code, or when the current request doesn’t match any view configuration. Pyramid provides a default implementation of a not found view; it can be overridden. See Changing the Not Found View. - package
- A directory on disk which contains an
__init__.py
file, making it recognizable to Python as a location which can beimport
-ed. A package exists to contain module files. - Pylons
- A lightweight Python web framework.
- Pyramid
- A web framework.
- renderer
- A serializer that can be referred to via view configuration which converts a non-Response return values from a view into a string (and ultimately a response). Using a renderer can make writing views that require templating or other serialization less tedious. See Writing View Callables Which Use a Renderer for more information.
- renderer factory
- A factory which creates a renderer. See Adding and Changing Renderers for more information.
- request
- A
WebOb
request object. See Request and Response Objects (narrative) and pyramid.request (API documentation) for information about request objects. - Resource Location
- The act of locating a context resource given a request. Traversal and URL dispatch are the resource location subsystems used by Pyramid.
- root factory
- The “root factory” of an Pyramid application is called
on every request sent to the application. The root factory
returns the traversal root of an application. It is
conventionally named
get_root
. An application may supply a root factory to Pyramid during the construction of a Configurator. If a root factory is not supplied, the application uses a default root object. Use of the default root object is useful in application which use URL dispatch for all URL-to-view code mappings. - route
- A single pattern matched by the url dispatch subsystem, which generally resolves to one or more view callable objects. See also url dispatch.
- route configuration
- Route configuration is the act of using imperative
configuration or a ZCML
<route>
statement to associate request parameters with a particular route using pattern matching and route predicate statements. See URL Dispatch for more information about route configuration. - route predicate
- An argument to a route configuration which implies a value
that evaluates to
True
orFalse
for a given request. All predicates attached to a route configuration must evaluate toTrue
for the associated route to “match” the current request. If a route does not match the current request, the next route (in definition order) is attempted. - router
- The WSGI application created when you start a Pyramid application. The router intercepts requests, invokes traversal and/or URL dispatch, calls view functions, and returns responses to the WSGI server on behalf of your Pyramid application.
- scan
- The term used by Pyramid to define the process of importing and examining all code in a Python package or module for configuration decoration.
- Translation Directory
- A translation directory is a gettext translation
directory. It contains language folders, which themselves
contain
LC_MESSAGES
folders, which contain.mo
files. Each.mo
file represents a set of translations for a language in a translation domain. The name of the.mo
file (minus the .mo extension) is the translation domain name. - Translation Domain
- A string representing the “context” in which a translation was
made. For example the word “java” might be translated
differently if the translation domain is “programming-languages”
than would be if the translation domain was “coffee”. A
translation domain is represnted by a collection of
.mo
files within one or more translation directory directories. - traversal
- The act of descending “up” a tree of resource objects from a root resource in order to find a context resource. The Pyramid router performs traversal of resource objects when a root factory is specified. See the Traversal chapter for more information. Traversal can be performed instead of URL dispatch or can be combined with URL dispatch. See Combining Traversal and URL Dispatch for more information about combining traversal and URL dispatch (advanced).
- URL dispatch
- An alternative to traversal as a mechanism for locating a a view callable. When you use a route in your Pyramid application via a route configuration, you are using URL dispatch. See the URL Dispatch for more information.
- view
- Common vernacular for a view callable.
- view callable
- A “view callable” is a callable Python object which is associated with a
view configuration; it returns a response object . A
view callable accepts a single argument:
request
, which will be an instance of a request object. A view callable is the primary mechanism by which a developer writes user interface code within Pyramid. See Views for more information about Pyramid view callables. - view configuration
- View configuration is the act of associating a view callable
with configuration information. This configuration information helps
map a given request to a particular view callable and it can
influence the response of a view callable. Pyramid views can be
configured via imperative configuration, ZCML or by a
special
@view_config
decorator coupled with a scan. See View Configuration for more information about view configuration. - View handler
- A view handler ties together
pyramid.config.Configurator.add_route()
andpyramid.config.Configurator.add_view()
to make it more convenient to register a collection of views as a single class when using url dispatch. See also Views. - view mapper
- A view mapper is a class which implements the
pyramid.interfaces.IViewMapperFactory
interface, which performs view argument and return value mapping. This is a plug point for extension builders, not normally used by “civilians”. - view name
- The “URL name” of a view, e.g
index.html
. If a view is configured without a name, its name is considered to be the empty string (which implies the default view). - view predicate
- An argument to a view configuration which evaluates to
True
orFalse
for a given request. All predicates attached to a view configuration must evaluate to true for the associated view to be considered as a possible callable for a given request. - WSGI
- Web Server Gateway Interface. This is a Python standard for connecting web applications to web servers, similar to the concept of Java Servlets. Pyramid requires that your application be served as a WSGI application.
- ZCML
- Zope Configuration Markup Language, an XML dialect
used by Zope and Pyramid for configuration tasks. ZCML
is capable of performing different types of configuration
declaration, but its primary purpose in Pyramid is to
perform view configuration and route configuration
within the
configure.zcml
file in a Pyramid application. You can use ZCML as an alternative to imperative configuration. - ZCML declaration
- The concrete use of a ZCML directive within a ZCML file.
- ZCML directive
- A ZCML “tag” such as
<view>
or<route>
. - Zope Component Architecture
- The Zope Component Architecture (aka ZCA) is a system which allows for application pluggability and complex dispatching based on objects which implement an interface. Pyramid uses the ZCA “under the hood” to perform view dispatching and other application configuration tasks.
Reporting Bugs / Development Versions¶
Visit http://github.com/Pylons/pyramid_zcml to download development or tagged versions.
Visit http://github.com/Pylons/pyramid_zcml/issues to report bugs.