Views¶
One of the primary jobs of Pyramid is to find and invoke a view callable when a request reaches your application. View callables are bits of code which do something interesting in response to a request made to your application. They are the "meat" of any interesting web application.
注釈
A Pyramid view callable is often referred to in conversational shorthand as a view. In this documentation, however, we need to use less ambiguous terminology because there are significant differences between view configuration, the code that implements a view callable, and the process of view lookup.
This chapter describes how view callables should be defined. We'll have to wait until a following chapter (entitled View Configuration) to find out how we actually tell Pyramid to wire up view callables to particular URL patterns and other request circumstances.
View Callables¶
View callables are, at the risk of sounding obvious, callable Python objects.
Specifically, view callables can be functions, classes, or instances that
implement a __call__
method (making the instance callable).
View callables must, at a minimum, accept a single argument named request
.
This argument represents a Pyramid Request object. A request
object represents a WSGI environment provided to Pyramid by the
upstream WSGI server. As you might expect, the request object contains
everything your application needs to know about the specific HTTP request being
made.
A view callable's ultimate responsibility is to create a Pyramid Response object. This can be done by creating a Response object in the view callable code and returning it directly or by raising special kinds of exceptions from within the body of a view callable.
Defining a View Callable as a Function¶
One of the easiest ways to define a view callable is to create a function that
accepts a single argument named request
, and which returns a
Response object. For example, this is a "hello world" view callable
implemented as a function:
1from pyramid.response import Response
2
3def hello_world(request):
4 return Response('Hello world!')
Defining a View Callable as a Class¶
A view callable may also be represented by a Python class instead of a
function. When a view callable is a class, the calling semantics are slightly
different than when it is a function or another non-class callable. When a view
callable is a class, the class's __init__
method is called with a
request
parameter. As a result, an instance of the class is created.
Subsequently, that instance's __call__
method is invoked with no
parameters. Views defined as classes must have the following traits.
an
__init__
method that accepts arequest
argumenta
__call__
(or other) method that accepts no parameters and which returns a response
For example:
1from pyramid.response import Response
2
3class MyView(object):
4 def __init__(self, request):
5 self.request = request
6
7 def __call__(self):
8 return Response('hello')
The request object passed to __init__
is the same type of request object
described in Defining a View Callable as a Function.
If you'd like to use a different attribute than __call__
to represent the
method expected to return a response, you can use an attr
value as part of
the configuration for the view. See View Configuration Parameters. The
same view callable class can be used in different view configuration statements
with different attr
values, each pointing at a different method of the
class if you'd like the class to represent a collection of related view
callables.
View Callable Responses¶
A view callable may return an object that implements the Pyramid
Response interface. The easiest way to return something that
implements the Response interface is to return a
pyramid.response.Response
object instance directly. For example:
1from pyramid.response import Response
2
3def view(request):
4 return Response('OK')
Pyramid provides a range of different "exception" classes which inherit
from pyramid.response.Response
. For example, an instance of the class
pyramid.httpexceptions.HTTPFound
is also a valid response object
because it inherits from Response
. For examples,
see HTTP Exceptions and Using a View Callable to do an HTTP Redirect.
注釈
You can also return objects from view callables that aren't instances of
pyramid.response.Response
in various circumstances. This can be
helpful when writing tests and when attempting to share code between view
callables. See Renderers for the common way to allow for
this. A much less common way to allow for view callables to return
non-Response objects is documented in Changing How Pyramid Treats View Responses.
Using Special Exceptions in View Callables¶
Usually when a Python exception is raised within a view callable, Pyramid allows the exception to propagate all the way out to the WSGI server which invoked the application. It is usually caught and logged there.
However, for convenience, a special set of exceptions exists. When one of these exceptions is raised within a view callable, it will always cause Pyramid to generate a response. These are known as HTTP exception objects.
HTTP Exceptions¶
All pyramid.httpexceptions
classes which are documented as inheriting
from the pyramid.httpexceptions.HTTPException
are http
exception objects. Instances of an HTTP exception object may either be
returned or raised from within view code. In either case (return or raise)
the instance will be used as the view's response.
For example, the pyramid.httpexceptions.HTTPUnauthorized
exception can
be raised. This will cause a response to be generated with a 401
Unauthorized
status:
1from pyramid.httpexceptions import HTTPUnauthorized
2
3def aview(request):
4 raise HTTPUnauthorized()
An HTTP exception, instead of being raised, can alternately be returned (HTTP exceptions are also valid response objects):
1from pyramid.httpexceptions import HTTPUnauthorized
2
3def aview(request):
4 return HTTPUnauthorized()
A shortcut for creating an HTTP exception is the
pyramid.httpexceptions.exception_response()
function. This function
accepts an HTTP status code and returns the corresponding HTTP exception. For
example, instead of importing and constructing a
HTTPUnauthorized
response object, you can use
the exception_response()
function to construct
and return the same object.
1from pyramid.httpexceptions import exception_response
2
3def aview(request):
4 raise exception_response(401)
This is the case because 401
is the HTTP status code for "HTTP
Unauthorized". Therefore, raise exception_response(401)
is functionally
equivalent to raise HTTPUnauthorized()
. Documentation which maps each HTTP
response code to its purpose and its associated HTTP exception object is
provided within pyramid.httpexceptions
.
バージョン 1.1 で追加: The exception_response()
function.
How Pyramid Uses HTTP Exceptions¶
HTTP exceptions are meant to be used directly by application developers. However, Pyramid itself will raise two HTTP exceptions at various points during normal operations.
HTTPNotFound
gets raised when a view to service a request is not found.HTTPForbidden
gets raised when authorization was forbidden by a security policy.
If HTTPNotFound
is raised by Pyramid itself or
within view code, the result of the Not Found View will be returned to
the user agent which performed the request.
If HTTPForbidden
is raised by Pyramid itself
or within view code, the result of the Forbidden View will be returned to
the user agent which performed the request.
Custom Exception Views¶
The machinery which allows HTTP exceptions to be raised and caught by specialized views as described in Using Special Exceptions in View Callables can also be used by application developers to convert arbitrary exceptions to responses.
To register an exception view that should be called whenever a
particular exception is raised from within Pyramid view code, use
pyramid.config.Configurator.add_exception_view()
to register a view
configuration which matches the exception (or a subclass of the exception) and
points at a view callable for which you'd like to generate a response. The
exception will be passed as the context
argument to any
view predicate registered with the view, as well as to the view itself.
For convenience a new decorator exists,
pyramid.views.exception_view_config
, which may be used to easily
register exception views.
For example, given the following exception class in a module named
helloworld.exceptions
:
1class ValidationFailure(Exception):
2 def __init__(self, msg):
3 self.msg = msg
You can wire a view callable to be called whenever any of your other code
raises a helloworld.exceptions.ValidationFailure
exception:
1from pyramid.view import exception_view_config
2from helloworld.exceptions import ValidationFailure
3
4@exception_view_config(ValidationFailure)
5def failed_validation(exc, request):
6 response = Response('Failed validation: %s' % exc.msg)
7 response.status_int = 500
8 return response
Assuming that a scan was run to pick up this view registration, this
view callable will be invoked whenever a
helloworld.exceptions.ValidationFailure
is raised by your application's
view code. The same exception raised by a custom root factory, a custom
traverser, or a custom view or route predicate is also caught and hooked.
Other normal view predicates can also be used in combination with an exception view registration:
1from pyramid.view import view_config
2from helloworld.exceptions import ValidationFailure
3
4@exception_view_config(ValidationFailure, route_name='home')
5def failed_validation(exc, request):
6 response = Response('Failed validation: %s' % exc.msg)
7 response.status_int = 500
8 return response
The above exception view names the route_name
of home
, meaning that it
will only be called when the route matched has a name of home
. You can
therefore have more than one exception view for any given exception in the
system: the "most specific" one will be called when the set of request
circumstances match the view registration.
The only view predicate that cannot be used successfully when creating an
exception view configuration is name
. The name used to look up an
exception view is always the empty string. Views registered as exception views
which have a name will be ignored.
注釈
In most cases, you should register an exception view by using
pyramid.config.Configurator.add_exception_view()
. However, it is
possible to register "normal" (i.e., non-exception) views against a context
resource type which inherits from Exception
(i.e.,
config.add_view(context=Exception)
). When the view configuration is
processed, two views are registered. One as a "normal" view, the other
as an exception view. This means that you can use an exception as
context
for a normal view.
The view derivers that wrap these two views may behave differently. See Exception Views and View Derivers for more information about this.
Exception views can be configured with any view registration mechanism:
@exception_view_config
decorator or imperative add_exception_view
styles.
注釈
Pyramid's exception view handling logic is implemented as a tween
factory function: pyramid.tweens.excview_tween_factory()
. If Pyramid
exception view handling is desired, and tween factories are specified via
the pyramid.tweens
configuration setting, the
pyramid.tweens.excview_tween_factory()
function must be added to the
pyramid.tweens
configuration setting list explicitly. If it is not
present, Pyramid will not perform exception view handling.
Using a View Callable to do an HTTP Redirect¶
You can issue an HTTP redirect by using the
pyramid.httpexceptions.HTTPFound
class. Raising or returning an
instance of this class will cause the client to receive a "302 Found" response.
To do so, you can return a pyramid.httpexceptions.HTTPFound
instance.
1from pyramid.httpexceptions import HTTPFound
2
3def myview(request):
4 return HTTPFound(location='http://example.com')
Alternately, you can raise an HTTPFound exception instead of returning one.
1from pyramid.httpexceptions import HTTPFound
2
3def myview(request):
4 raise HTTPFound(location='http://example.com')
When the instance is raised, it is caught by the default exception response handler and turned into a response.
Handling Form Submissions in View Callables (Unicode and Character Set Issues)¶
Most web applications need to accept form submissions from web browsers and various other clients. In Pyramid, form submission handling logic is always part of a view. For a general overview of how to handle form submission data using the WebOb API, see Request and Response Objects and "Query and POST variables" within the WebOb documentation. Pyramid defers to WebOb for its request and response implementations, and handling form submission data is a property of the request implementation. Understanding WebOb's request API is the key to understanding how to process form submission data.
There are some defaults that you need to be aware of when trying to handle form
submission data in a Pyramid view. Having high-order (i.e., non-ASCII)
characters in data contained within form submissions is exceedingly common, and
the UTF-8 encoding is the most common encoding used on the web for character
data. Since Unicode values are much saner than working with and storing
bytestrings, Pyramid configures the WebOb request machinery to
attempt to decode form submission values into Unicode from UTF-8 implicitly.
This implicit decoding happens when view code obtains form field values via the
request.params
, request.GET
, or request.POST
APIs (see
pyramid.request for details about these APIs).
注釈
Many people find the difference between Unicode and UTF-8 confusing. Unicode is a standard for representing text that supports most of the world's writing systems. However, there are many ways that Unicode data can be encoded into bytes for transit and storage. UTF-8 is a specific encoding for Unicode that is backwards-compatible with ASCII. This makes UTF-8 very convenient for encoding data where a large subset of that data is ASCII characters, which is largely true on the web. UTF-8 is also the standard character encoding for URLs.
As an example, let's assume that the following form page is served up to a
browser client, and its action
points at some Pyramid view code:
1<html xmlns="http://www.w3.org/1999/xhtml">
2 <form method="POST" action="myview" accept-charset="UTF-8">
3 <div>
4 <input type="text" name="firstname"/>
5 </div>
6 <div>
7 <input type="text" name="lastname"/>
8 </div>
9 <input type="submit" value="Submit"/>
10 </form>
11</html>
The myview
view code in the Pyramid application must expect that
the values returned by request.params
will be of type str
, as opposed
to type bytes
. The following will work to accept a form post from the
above form:
1def myview(request):
2 firstname = request.params['firstname']
3 lastname = request.params['lastname']
For implicit decoding to work reliably, you should ensure that every form you
render that posts to a Pyramid view explicitly defines a charset
encoding of UTF-8. This can be done via a response that has a
;charset=UTF-8
in its Content-Type
header; or, as in the form above,
with an accept-charset
attribute, informing the browser that the
server expects the form content to be encoded using UTF-8. This must be done
explicitly because all known browser clients assume that they should encode
form data in the same character set implied by the Content-Type
value of
the response containing the form when subsequently submitting that form. There
is no other generally accepted way to tell browser clients which charset to use
to encode form data. If you do not specify an encoding explicitly, the browser
client will choose to encode form data in its default character set before
submitting it, which may not be UTF-8 as the server expects. If a request
containing form data encoded in a non-UTF-8 charset
is handled by your view
code, eventually the request code accessed within your view will throw an error
when it can't decode some high-order character encoded in another character set
within form data, e.g., when request.params['somename']
is accessed.
If you are using the Response
class to generate a
response, or if you use the pyramid.renderers.render_*
templating APIs,
the UTF-8 charset
is set automatically as the default via the
Content-Type
header. If you return a Content-Type
header without an
explicit charset
, a request will add a ;charset=utf-8
trailer to the
Content-Type
header value for you for response content types that are
textual (e.g., text/html
or application/xml
) as it is rendered. If you
are using your own response object, you will need to ensure you do this
yourself.
Alternate View Callable Argument/Calling Conventions¶
Usually view callables are defined to accept only a single argument:
request
. However, a view callable may alternately be defined as any class, function, or callable that accepts two positional arguments: a
context resource as the first argument and a request as the
second argument.
The context and request arguments passed to a view function defined in this style can be defined as follows:
- context
The resource object found via tree traversal or URL dispatch.
- request
A Pyramid Request object representing the current WSGI request.
The following types work as view callables in this style:
Functions that accept two arguments:
context
andrequest
, e.g.:1from pyramid.response import Response 2 3def view(context, request): 4 return Response('OK')
Classes that have an
__init__
method that acceptscontext, request
, and a__call__
method which accepts no arguments, e.g.:1from pyramid.response import Response 2 3class view(object): 4 def __init__(self, context, request): 5 self.context = context 6 self.request = request 7 8 def __call__(self): 9 return Response('OK')
Arbitrary callables that have a
__call__
method that acceptscontext, request
, e.g.:1from pyramid.response import Response 2 3class View(object): 4 def __call__(self, context, request): 5 return Response('OK') 6view = View() # this is the view callable
This style of calling convention is most useful for traversal based applications, where the context object is frequently used within the view callable code itself.
No matter which view calling convention is used, the view code always has
access to the context via request.context
.
Passing Configuration Variables to a View¶
For information on passing a variable from the configuration .ini files to a view, see Deployment Settings.
Pylons-1.0-Style "Controller" Dispatch¶
A package named pyramid_handlers (available from PyPI) provides an analogue of Pylons-style "controllers", which are a special kind of view class which provides more automation when your application uses URL dispatch solely.