What's New in Pyramid 1.1¶
This article explains the new features in Pyramid version 1.1 as compared to its predecessor, Pyramid 1.0. It also documents backwards incompatibilities between the two versions and deprecations added to Pyramid 1.1, as well as software dependency changes and notable documentation additions.
Terminology Changes¶
The term "template" used by the Pyramid documentation used to refer to both "paster templates" and "rendered templates" (templates created by a rendering engine. i.e. Mako, Chameleon, Jinja, etc.). "Paster templates" will now be referred to as "scaffolds", whereas the name for "rendered templates" will remain as "templates."
Major Feature Additions¶
The major feature additions in Pyramid 1.1 are:
Support for the
request.responseattribute.New views introspection feature:
paster pviews.Support for "static" routes.
Default HTTP exception view.
http_cacheview configuration parameter causes Pyramid to set HTTP caching headers.Features that make it easier to write scripts that work in a Pyramid environment.
request.response¶
Instances of the
pyramid.request.Requestclass now have aresponseattribute.The object passed to a view callable as
requestis an instance ofpyramid.request.Request.request.responseis an instance of the classpyramid.response.Response. View callables that are configured with a renderer will return this response object to the Pyramid router. Therefore, code in a renderer-using view callable can set response attributes such asrequest.response.content_type(before they return, e.g. a dictionary to the renderer) and this will influence the HTTP return value of the view callable.request.responsecan also be used in view callable code that is not configured to use a renderer. For example, a view callable might dorequest.response.body = '123'; return request.response. However, the response object that is produced byrequest.responsemust be returned when a renderer is not in play in order to have any effect on the HTTP response (it is not a "global" response, and modifications to it are not somehow merged into a separately returned response object).The
request.responseobject is lazily created, so its introduction does not negatively impact performance.
paster pviews¶
A new paster command named
paster pviewswas added. This command prints a summary of potentially matching views for a given path. See the section entitled pviews: Displaying Matching Views for a Given URL for more information.
Static Routes¶
The
add_routemethod of the Configurator now accepts astaticargument. If this argument isTrue, the added route will never be considered for matching when a request is handled. Instead, it will only be useful for URL generation viaroute_urlandroute_path. See the section entitled Static Routes for more information.
Default HTTP Exception View¶
A default exception view for the interface
pyramid.interfaces.IExceptionResponseis now registered by default. This means that an instance of any exception class imported frompyramid.httpexceptions(such asHTTPFound) can now be raised from within view code; when raised, this exception view will render the exception to a response.To allow for configuration of this feature, the Configurator now accepts an additional keyword argument named
exceptionresponse_view. By default, this argument is populated with a default exception view function that will be used when an HTTP exception is raised. WhenNoneis passed for this value, an exception view for HTTP exceptions will not be registered. PassingNonereturns the behavior of raising an HTTP exception to that of Pyramid 1.0 (the exception will propagate to middleware and to the WSGI server).
http_cache¶
A new value http_cache can be used as a view configuration
parameter.
When you supply an http_cache value to a view configuration, the
Expires and Cache-Control headers of a response generated by the
associated view callable are modified. The value for http_cache may be
one of the following:
A nonzero integer. If it's a nonzero integer, it's treated as a number of seconds. This number of seconds will be used to compute the
Expiresheader and theCache-Control: max-ageparameter of responses to requests which call this view. For example:http_cache=3600instructs the requesting browser to 'cache this response for an hour, please'.A
datetime.timedeltainstance. If it's adatetime.timedeltainstance, it will be converted into a number of seconds, and that number of seconds will be used to compute theExpiresheader and theCache-Control: max-ageparameter of responses to requests which call this view. For example:http_cache=datetime.timedelta(days=1)instructs the requesting browser to 'cache this response for a day, please'.Zero (
0). If the value is zero, theCache-ControlandExpiresheaders present in all responses from this view will be composed such that client browser cache (and any intermediate caches) are instructed to never cache the response.A two-tuple. If it's a two tuple (e.g.
http_cache=(1, {'public':True})), the first value in the tuple may be a nonzero integer or adatetime.timedeltainstance; in either case this value will be used as the number of seconds to cache the response. The second value in the tuple must be a dictionary. The values present in the dictionary will be used as input to theCache-Controlresponse header. For example:http_cache=(3600, {'public':True})means 'cache for an hour, and addpublicto the Cache-Control header of the response'. All keys and values supported by thewebob.cachecontrol.CacheControlinterface may be added to the dictionary. Supplying{'public':True}is equivalent to callingresponse.cache_control.public = True.
Providing a non-tuple value as http_cache is equivalent to calling
response.cache_expires(value) within your view's body.
Providing a two-tuple value as http_cache is equivalent to calling
response.cache_expires(value[0], **value[1]) within your view's body.
If you wish to avoid influencing, the Expires header, and instead wish
to only influence Cache-Control headers, pass a tuple as http_cache
with the first element of None, e.g.: (None, {'public':True}).
The environment setting PYRAMID_PREVENT_HTTP_CACHE and configuration
file value prevent_http_cache are synonymous and allow you to prevent
HTTP cache headers from being set by Pyramid's http_cache machinery
globally in a process. see Influencing HTTP Caching and
Preventing HTTP Caching.
Easier Scripting Writing¶
A new API function pyramid.paster.bootstrap() has been added to make
writing scripts that need to work under Pyramid environment easier, e.g.:
from pyramid.paster import bootstrap
info = bootstrap('/path/to/my/development.ini')
request = info['request']
print request.route_url('myroute')
See Writing a Script for more details.
Minor Feature Additions¶
It is now possible to invoke
paster pshelleven if the paste ini file section name pointed to in its argument is not actually a Pyramid WSGI application. The shell will work in a degraded mode, and will warn the user. See "The Interactive Shell" in the "Creating a Pyramid Project" narrative documentation section.The
paster pshell,paster pviews, andpaster proutescommands each now under the hood usespyramid.paster.bootstrap(), which makes it possible to supply an.inifile without naming the "right" section in the file that points at the actual Pyramid application. Instead, you can generally just runpaster {pshell|proutes|pviews} development.iniand it will do mostly the right thing.It is now possible to add a
[pshell]section to your application's .ini configuration file, which influences the global names available to a pshell session. See Extending the Shell.The
pyramid.config.Configurator.scan()method has grown a**kwargument.kwargument represents a set of keyword arguments to pass to the VenusianScannerobject created by Pyramid. (See the Venusian documentation for more information aboutScanner).New request property:
json_body. This property will return the JSON-decoded variant of the request body. If the request body is not well-formed JSON, this property will raise an exception.A JSONP renderer. See JSONP Renderer for more details.
New authentication policy:
pyramid.authentication.SessionAuthenticationPolicy, which uses a session to store credentials.A function named
pyramid.httpexceptions.exception_response()is a shortcut that can be used to create HTTP exception response objects using an HTTP integer status code.Integers and longs passed as
elementstopyramid.url.resource_url()orpyramid.request.Request.resource_url()e.g.resource_url(context, request, 1, 2)(1and2are theelements) will now be converted implicitly to strings in the result. Previously passing integers or longs as elements would cause a TypeError.pyramid_alchemyscaffold now usesquery.getrather thanquery.filter_byto take better advantage of identity map caching.pyramid_alchemyscaffold now has unit tests.Added a
pyramid.i18n.make_localizer()API.An exception raised by a
pyramid.events.NewRequestevent subscriber can now be caught by an exception view.It is now possible to get information about why Pyramid raised a Forbidden exception from within an exception view. The
ACLDeniedobject returned by thepermitsmethod of each stock authorization policy (pyramid.interfaces.IAuthorizationPolicy.permits()) is now attached to the Forbidden exception as itsresultattribute. Therefore, if you've created a Forbidden exception view, you can see the ACE, ACL, permission, and principals involved in the request as eg.context.result.permission,context.result.acl, etc within the logic of the Forbidden exception view.Don't explicitly prevent the
timeoutfrom being lower than thereissue_timewhen setting up anpyramid.authentication.AuthTktAuthenticationPolicy(previously such a configuration would raise aValueError, now it's allowed, although typically nonsensical). Allowing the nonsensical configuration made the code more understandable and required fewer tests.The
pyramid.request.Requestclass now has aResponseClassattribute which points atpyramid.response.Response.The
pyramid.response.Responseclass now has aRequestClassinterface which points atpyramid.request.Request.It is now possible to return an arbitrary object from a Pyramid view callable even if a renderer is not used, as long as a suitable adapter to
pyramid.interfaces.IResponseis registered for the type of the returned object by using the newpyramid.config.Configurator.add_response_adapter()API. See the section in the Hooks chapter of the documentation entitled Changing How Pyramid Treats View Responses.The Pyramid router will now, by default, call the
__call__method of response objects when returning a WSGI response. This means that, among other things, theconditional_responsefeature response objects inherited from WebOb will now behave properly.New method named
pyramid.request.Request.is_response(). This method should be used instead of thepyramid.view.is_response()function, which has been deprecated.pyramid.exceptions.NotFoundis now just an alias forpyramid.httpexceptions.HTTPNotFound.pyramid.exceptions.Forbiddenis now just an alias forpyramid.httpexceptions.HTTPForbidden.Added
mako.preprocessorconfig file parameter; allows for a Mako preprocessor to be specified as a Python callable or Python dotted name. See https://github.com/Pylons/pyramid/pull/183 for rationale.New API class:
pyramid.static.static_view. This supersedes the (now deprecated)pyramid.view.staticclass.pyramid.static.static_view, by default, serves up documents as the result of the request'spath_info, attribute rather than it'ssubpathattribute (the inverse was true ofpyramid.view.static, and still is).pyramid.static.static_viewexposes ause_subpathflag for use when you want the static view to behave like the older deprecated version.A new api function
pyramid.scripting.prepare()has been added. It is a lower-level analogue ofpyramid.paster.bootstrap()that accepts a request and a registry instead of a config file argument, and is used for the same purpose:from pyramid.scripting import prepare info = prepare(registry=myregistry) request = info['request'] print request.route_url('myroute')
A new API function
pyramid.scripting.make_request()has been added. The resulting request will have aregistryattribute. It is meant to be used in conjunction withpyramid.scripting.prepare()and/orpyramid.paster.bootstrap()(both of which accept a request as an argument):from pyramid.scripting import make_request request = make_request('/')
New API attribute
pyramid.config.global_registriesis an iterable object that contains references to every Pyramid registry loaded into the current process viapyramid.config.Configurator.make_wsgi_app(). It also has alastattribute containing the last registry loaded. This is used by the scripting machinery, and is available for introspection.Added the
pyramid.renderers.null_rendererobject as an API. The null renderer is an object that can be used in advanced integration cases as input to the view configurationrenderer=argument. When the null renderer is used as a view renderer argument, Pyramid avoids converting the view callable result into a Response object. This is useful if you want to reuse the view configuration and lookup machinery outside the context of its use by the Pyramid router. (This feature was added for consumption by thepyramid_rpcpackage, which uses view configuration and lookup outside the context of a router in exactly this way.)
Backwards Incompatibilities¶
Pyramid no longer supports Python 2.4. Python 2.5 or better is required to run Pyramid 1.1+. Pyramid, however, does not work under any version of Python 3 yet.
The Pyramid router now, by default, expects response objects returned from view callables to implement the
pyramid.interfaces.IResponseinterface. Unlike the Pyramid 1.0 version of this interface, objects which implement IResponse now must define a__call__method that acceptsenvironandstart_response, and which returns anapp_iteriterable, among other things. Previously, it was possible to return any object which had the three WebObapp_iter,headerlist, andstatusattributes as a response, so this is a backwards incompatibility. It is possible to get backwards compatibility back by registering an adapter to IResponse from the type of object you're now returning from view callables. See the section in the Hooks chapter of the documentation entitled Changing How Pyramid Treats View Responses.The
pyramid.interfaces.IResponseinterface is now much more extensive. Previously it defined onlyapp_iter,statusandheaderlist; now it is basically intended to directly mirror thewebob.ResponseAPI, which has many methods and attributes.The
pyramid.httpexceptionsclasses namedHTTPFound,HTTPMultipleChoices,HTTPMovedPermanently,HTTPSeeOther,HTTPUseProxy, andHTTPTemporaryRedirectnow acceptlocationas their first positional argument rather thandetail. This means that you can do, e.g.return pyramid.httpexceptions.HTTPFound('http://foo')rather thanreturn pyramid.httpexceptions.HTTPFound(location='http//foo')(the latter will of course continue to work).The pyramid Router attempted to set a value into the key
environ['repoze.bfg.message']when it caught a view-related exception for backwards compatibility with applications written forrepoze.bfgduring error handling. It did this by using code that looked like so:# "why" is an exception object try: msg = why[0] except: msg = '' environ['repoze.bfg.message'] = msg
Use of the value
environ['repoze.bfg.message']was docs-deprecated in Pyramid 1.0. Our standing policy is to not remove features after a deprecation for two full major releases, so this code was originally slated to be removed in Pyramid 1.2. However, computing therepoze.bfg.messagevalue was the source of at least one bug found in the wild (https://github.com/Pylons/pyramid/issues/199), and there isn't a foolproof way to both preserve backwards compatibility and to fix the bug. Therefore, the code which sets the value has been removed in this release. Code in exception views which relies on this value's presence in the environment should now use theexceptionattribute of the request (e.g.request.exception[0]) to retrieve the message instead of relying onrequest.environ['repoze.bfg.message'].
Deprecations and Behavior Differences¶
Note
Under Python 2.7+, it's necessary to pass the Python interpreter
the correct warning flags to see deprecation warnings emitted by Pyramid
when porting your application from an older version of Pyramid. Use the
PYTHONWARNINGS environment variable with the value all in the
shell you use to invoke paster serve to see these warnings, e.g. on
Unix, PYTHONWARNINGS=all $VENV/bin/paster serve development.ini.
Python 2.5 and 2.6 show deprecation warnings by default,
so this is unnecessary there.
All deprecation warnings are emitted to the console.
The
pyramid.view.staticclass has been deprecated in favor of the newerpyramid.static.static_viewclass. A deprecation warning is raised when it is used. You should replace it with a reference topyramid.static.static_viewwith theuse_subpath=Trueargument.The
paster pshell,paster proutes, andpaster pviewscommands now take a single argument in the form/path/to/config.ini#sectionnamerather than the previous 2-argument spelling/path/to/config.ini sectionname.#sectionnamemay be omitted, in which case#mainis assumed.The default Mako renderer is now configured to escape all HTML in expression tags. This is intended to help prevent XSS attacks caused by rendering unsanitized input from users. To revert this behavior in user's templates, they need to filter the expression through the 'n' filter:
${ myhtml | n }.Deprecated all assignments to
request.response_*attributes (for examplerequest.response_content_type = 'foo'is now deprecated). Assignments and mutations of assignable request attributes that were considered by the framework for response influence are now deprecated:response_content_type,response_headerlist,response_status,response_charset, andresponse_cache_for. Instead of assigning these to the request object for later detection by the rendering machinery, users should use the appropriate API of the Response object created by accessingrequest.response(e.g. code which doesrequest.response_content_type = 'abc'should be changed torequest.response.content_type = 'abc').Passing view-related parameters to
pyramid.config.Configurator.add_route()is now deprecated. Previously, a view was permitted to be connected to a route using a set ofview*parameters passed to theadd_routemethod of the Configurator. This was a shorthand which replaced the need to perform a subsequent call toadd_view. For example, it was valid (and often recommended) to do:config.add_route('home', '/', view='mypackage.views.myview', view_renderer='some/renderer.pt')
Passing
view*arguments toadd_routeis now deprecated in favor of connecting a view to a predefined route viapyramid.config.Configurator.add_view()using the route'sroute_nameparameter. As a result, the above example should now be spelled:config.add_route('home', '/') config.add_view('mypackage.views.myview', route_name='home', renderer='some/renderer.pt')
This deprecation was done to reduce confusion observed in IRC, as well as to (eventually) reduce documentation burden. A deprecation warning is now issued when any view-related parameter is passed to
add_route.See also
See also issue #164 on GitHub.
Passing an
environdictionary to the__call__method of a "traverser" (e.g. an object that implementspyramid.interfaces.ITraversersuch as an instance ofpyramid.traversal.ResourceTreeTraverser) as itsrequestargument now causes a deprecation warning to be emitted. Consumer code should pass arequestobject instead. The fact that passing an environ dict is permitted has been documentation-deprecated sincerepoze.bfg1.1, and this capability will be removed entirely in a future version.The following (undocumented, dictionary-like) methods of the
pyramid.request.Requestobject have been deprecated:__contains__,__delitem__,__getitem__,__iter__,__setitem__,get,has_key,items,iteritems,itervalues,keys,pop,popitem,setdefault,update, andvalues. Usage of any of these methods will cause a deprecation warning to be emitted. These methods were added for internal compatibility inrepoze.bfg1.1 (code that currently expects a request object expected an environ object in BFG 1.0 and before). In a future version, these methods will be removed entirely.A custom request factory is now required to return a request object that has a
responseattribute (or "reified"/lazy property) if the request is meant to be used in a view that uses a renderer. Thisresponseattribute should be an instance of the classpyramid.response.Response.The JSON and string renderer factories now assign to
request.response.content_typerather thanrequest.response_content_type.Each built-in renderer factory now determines whether it should change the content type of the response by comparing the response's content type against the response's default content type; if the content type is the default content type (usually
text/html), the renderer changes the content type (toapplication/jsonortext/plainfor JSON and string renderers respectively).The
pyramid.wsgi.wsgiapp2()now uses a slightly different method of figuring out how to "fix"SCRIPT_NAMEandPATH_INFOfor the downstream application. As a result, those values may differ slightly from the perspective of the downstream application (for example,SCRIPT_NAMEwill now never possess a trailing slash).Previously,
pyramid.request.Requestinherited fromwebob.request.Requestand implemented__getattr__,__setattr__and__delattr__itself in order to override "adhoc attr" WebOb behavior where attributes of the request are stored in the environ. Now,pyramid.request.Requestinherits from (the more recent)webob.request.BaseRequestinstead ofwebob.request.Request, which provides the same behavior.pyramid.request.Requestno longer implements its own__getattr__,__setattr__or__delattr__as a result.Deprecated
pyramid.view.is_response()function in favor of (newly-added)pyramid.request.Request.is_response()method. Determining if an object is truly a valid response object now requires access to the registry, which is only easily available as a request attribute. Thepyramid.view.is_response()function will still work until it is removed, but now may return an incorrect answer under some (very uncommon) circumstances.pyramid.response.Responseis now a subclass ofwebob.response.Response(in order to directly implement thepyramid.interfaces.IResponseinterface, to speed up response generation).The "exception response" objects importable from
pyramid.httpexceptions(e.g.HTTPNotFound) are no longer just import aliases for classes that actually live inwebob.exc. Instead, we've defined our own exception classes within the module that mirror and emulate thewebob.excexception response objects almost entirely. See Pyramid uses its own HTTP exception class hierarchy rather than webob.exc in the Design Defense chapter for more information.When visiting a URL that represented a static view which resolved to a subdirectory, the
index.htmlof that subdirectory would not be served properly. Instead, a redirect to/subdirwould be issued. This has been fixed, and now visiting a subdirectory that contains anindex.htmlwithin a static view returns the index.html properly.See also
See also issue #67 on GitHub.
Deprecated the
pyramid.config.Configurator.set_renderer_globals_factorymethod and therenderer_globalsConfigurator constructor parameter. Users should convert code using this feature to use a BeforeRender event. See the section Using the Before Render Event in the Hooks chapter.In Pyramid 1.0, the
pyramid.events.subscriberdirective behaved contrary to the documentation when passed more than one interface object to its constructor. For example, when the following listener was registered:@subscriber(IFoo, IBar) def expects_ifoo_events_and_ibar_events(event): print event
The Events chapter docs claimed that the listener would be registered and listening for both
IFooandIBarevents. Instead, it registered an "object event" subscriber which would only be called if an IObjectEvent was emitted where the object interface wasIFooand the event interface wasIBar.The behavior now matches the documentation. If you were relying on the buggy behavior of the 1.0
subscriberdirective in order to register an object event subscriber, you must now pass a sequence to indicate you'd like to register a subscriber for an object event. e.g.:@subscriber([IFoo, IBar]) def expects_object_event(object, event): print object, event
In 1.0, if a
pyramid.events.BeforeRenderevent subscriber added a value via the__setitem__orupdatemethods of the event object with a key that already existed in the renderer globals dictionary, aKeyErrorwas raised. With the deprecation of the "add_renderer_globals" feature of the configurator, there was no way to override an existing value in the renderer globals dictionary that already existed. Now, the event object will overwrite an older value that is already in the globals dictionary when its__setitem__orupdateis called (as well as the newsetdefaultmethod), just like a plain old dictionary. As a result, for maximum interoperability with other third-party subscribers, if you write an event subscriber meant to be used as a BeforeRender subscriber, your subscriber code will now need to (using.getor__contains__of the event object) ensure no value already exists in the renderer globals dictionary before setting an overriding value.The
pyramid.config.Configurator.add_route()method allowed two routes with the same route to be added without an intermediate call topyramid.config.Configurator.commit(). If you now receive aConfigurationErrorat startup time that appears to beadd_routerelated, you'll need to either a) ensure that all of your route names are unique or b) callconfig.commit()before adding a second route with the name of a previously added name or c) use a Configurator that works inautocommitmode.
Dependency Changes¶
Pyramid now depends on WebOb >= 1.0.2 as tests depend on the bugfix in that release: "Fix handling of WSGI environs with missing
SCRIPT_NAME". (Note that in reality, everyone should probably be using 1.0.4 or better though, as WebOb 1.0.2 and 1.0.3 were effectively brownbag releases.)
Documentation Enhancements¶
Added a section entitled Writing a Script to the "Command-Line Pyramid" chapter.
The ZODB + Traversal Wiki Tutorial was updated slightly.
The SQLAlchemy + URL dispatch wiki tutorial was updated slightly.
Made
pyramid.interfaces.IAuthenticationPolicyandpyramid.interfaces.IAuthorizationPolicypublic interfaces, and they are now referred to within thepyramid.authenticationandpyramid.authorizationAPI docs.Render the function definitions for each exposed interface in
pyramid.interfaces.Add missing docs reference to
pyramid.config.Configurator.set_view_mapper()and refer to it within the documentation section entitled Using a View Mapper.Added section to the "Environment Variables and
.iniFile Settings" chapter in the narrative documentation section entitled Adding a Custom Setting.Added documentation for a multidict as
pyramid.interfaces.IMultiDict.Added a section to the "URL Dispatch" narrative chapter regarding the new "static" route feature entitled Static Routes.
Added API docs for
pyramid.httpexceptions.exception_response().Added HTTP Exceptions section to Views narrative chapter including a description of
pyramid.httpexceptions.exception_response().Added API docs for
pyramid.authentication.SessionAuthenticationPolicy.