Request / Response Objects

优质
小牛编辑
127浏览
2023-12-01

The request and response objects wrap the WSGI environment or the return value from a WSGI application so that it is another WSGI application (wraps a whole application).

How they Work

Your WSGI application is always passed two arguments. The WSGI “environment” and the WSGI start_response function that is used to start the response phase. The werkzeug.wrappers.Request" title="werkzeug.wrappers.Request class wraps the environ for easier access to request variables (form data, request headers etc.).

The werkzeug.wrappers.Response" title="werkzeug.wrappers.Response on the other hand is a standard WSGI application that you can create. The simple hello world in Werkzeug looks like this:

from werkzeug.wrappers import Response
application = Response('Hello World!')

To make it more useful you can replace it with a function and do some processing:

from werkzeug.wrappers import Request, Response

def application(environ, start_response):
    request = Request(environ)
    response = Response("Hello %s!" % request.args.get('name', 'World!'))
    return response(environ, start_response)

Because this is a very common task the werkzeug.wrappers.Request" title="werkzeug.wrappers.Request object provides a helper for that. The above code can be rewritten like this:

from werkzeug.wrappers import Request, Response

@Request.application
def application(request):
    return Response("Hello %s!" % request.args.get('name', 'World!'))

The application is still a valid WSGI application that accepts the environment and start_response callable.

Mutability and Reusability of Wrappers

The implementation of the Werkzeug request and response objects are trying to guard you from common pitfalls by disallowing certain things as much as possible. This serves two purposes: high performance and avoiding of pitfalls.

For the request object the following rules apply:

  1. The request object is immutable. Modifications are not supported by default, you may however replace the immutable attributes with mutable attributes if you need to modify it.
  2. The request object may be shared in the same thread, but is not thread safe itself. If you need to access it from multiple threads, use locks around calls.
  3. It’s not possible to pickle the request object.

For the response object the following rules apply:

  1. The response object is mutable
  2. The response object can be pickled or copied after freeze() was called.
  3. Since Werkzeug 0.6 it’s safe to use the same response object for multiple WSGI responses.
  4. It’s possible to create copies using copy.deepcopy.

Base Wrappers

These objects implement a common set of operations. They are missing fancy addon functionality like user agent parsing or etag handling. These features are available by mixing in various mixin classes or using werkzeug.wrappers.Request" title="werkzeug.wrappers.Request and werkzeug.wrappers.Response" title="werkzeug.wrappers.Response.

class werkzeug.wrappers.BaseRequest(environ, populate_request=True, shallow=False)

Werkzeug also provides helper mixins for various HTTP related functionality such as etags, cache control, user agents etc. When subclassing you can mix those classes in to extend the functionality of the werkzeug.wrappers.BaseRequest" title="werkzeug.wrappers.BaseRequest or werkzeug.wrappers.BaseResponse" title="werkzeug.wrappers.BaseResponse object. Here a small example for a request object that parses accept headers:

from werkzeug.wrappers import AcceptMixin, BaseRequest

class Request(BaseRequest, AcceptMixin):
    pass

The werkzeug.wrappers.Request" title="werkzeug.wrappers.Request and werkzeug.wrappers.Response" title="werkzeug.wrappers.Response classes subclass the werkzeug.wrappers.BaseRequest" title="werkzeug.wrappers.BaseRequest and werkzeug.wrappers.BaseResponse" title="werkzeug.wrappers.BaseResponse classes and implement all the mixins Werkzeug provides:

class werkzeug.wrappers.Request(environ, populate_request=True, shallow=False)

Full featured request object implementing the following mixins:

  • werkzeug.wrappers.AcceptMixin" title="werkzeug.wrappers.AcceptMixin for accept header parsing
  • werkzeug.wrappers.ETagRequestMixin" title="werkzeug.wrappers.ETagRequestMixin for etag and cache control handling
  • werkzeug.wrappers.UserAgentMixin" title="werkzeug.wrappers.UserAgentMixin for user agent introspection
  • werkzeug.wrappers.AuthorizationMixin" title="werkzeug.wrappers.AuthorizationMixin for http auth handling
  • werkzeug.wrappers.CommonRequestDescriptorsMixin" title="werkzeug.wrappers.CommonRequestDescriptorsMixin for common headers
class werkzeug.wrappers.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

Full featured response object implementing the following mixins:

  • werkzeug.wrappers.ETagResponseMixin" title="werkzeug.wrappers.ETagResponseMixin for etag and cache control handling
  • werkzeug.wrappers.ResponseStreamMixin" title="werkzeug.wrappers.ResponseStreamMixin to add support for the stream property
  • werkzeug.wrappers.CommonResponseDescriptorsMixin" title="werkzeug.wrappers.CommonResponseDescriptorsMixin for various HTTP descriptors
  • werkzeug.wrappers.WWWAuthenticateMixin" title="werkzeug.wrappers.WWWAuthenticateMixin for HTTP authentication support
class werkzeug.wrappers.AcceptMixin

A mixin for classes with an environ attribute to get all the HTTP accept headers as Accept objects (or subclasses thereof).

accept_charsets

List of charsets this client supports as CharsetAccept object.

accept_encodings

List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset.

accept_languages

List of languages this client accepts as LanguageAccept object.

accept_mimetypes

List of mimetypes this client supports as MIMEAccept object.

class werkzeug.wrappers.AuthorizationMixin

Adds an werkzeug.wrappers.AuthorizationMixin.authorization" title="werkzeug.wrappers.AuthorizationMixin.authorization property that represents the parsed value of the Authorization header as Authorization object.

authorization

The Authorization object in parsed form.

class werkzeug.wrappers.ETagRequestMixin

Add entity tag and cache descriptors to a request object or object with a WSGI environment available as werkzeug.wrappers.BaseRequest.environ" title="werkzeug.wrappers.BaseRequest.environ. This not only provides access to etags but also to the cache control header.

cache_control

A RequestCacheControl object for the incoming cache control headers.

if_match

An object containing all the etags in the If-Match header.

返回类型:ETags
if_modified_since

The parsed If-Modified-Since header as datetime object.

if_none_match

An object containing all the etags in the If-None-Match header.

返回类型:ETags
if_range

The parsed If-Range header.

0.7 新版功能.

返回类型:IfRange
if_unmodified_since

The parsed If-Unmodified-Since header as datetime object.

range

The parsed Range header.

0.7 新版功能.

返回类型:Range
class werkzeug.wrappers.ETagResponseMixin

Adds extra functionality to a response object for etag and cache handling. This mixin requires an object with at least a headers object that implements a dict like interface similar to Headers.

If you want the werkzeug.wrappers.ETagResponseMixin.freeze" title="werkzeug.wrappers.ETagResponseMixin.freeze method to automatically add an etag, you have to mixin this method before the response base class. The default response class does not do that.

accept_ranges

The Accept-Ranges header. Even though the name would indicate that multiple values are supported, it must be one string token only.

The values 'bytes' and 'none' are common.

0.7 新版功能.

add_etag(overwrite=False, weak=False)

Add an etag for the current response if there is none yet.

cache_control

The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.

content_range

The Content-Range header as ContentRange object. Even if the header is not set it wil provide such an object for easier manipulation.

0.7 新版功能.

freeze(no_etag=False)

Call this method if you want to make your response object ready for pickeling. This buffers the generator if there is one. This also sets the etag unless no_etag is set to True.

get_etag()

Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).

make_conditional(request_or_environ)

Make the response conditional to the request. This method works best if an etag was defined for the response already. The add_etag method can be used to do that. If called without etag just the date header is set.

This does nothing if the request method in the request or environ is anything but GET or HEAD.

It does not remove the body of the response because that’s something the __call__() function does for us automatically.

Returns self so that you can do return resp.make_conditional(req) but modifies the object in-place.

参数:request_or_environ – a request object or WSGI environment to be used to make the response conditional against.
set_etag(etag, weak=False)

Set the etag, and override the old one if there was one.

class werkzeug.wrappers.ResponseStreamMixin

Mixin for werkzeug.wrappers.BaseRequest" title="werkzeug.wrappers.BaseRequest subclasses. Classes that inherit from this mixin will automatically get a werkzeug.wrappers.ResponseStreamMixin.stream" title="werkzeug.wrappers.ResponseStreamMixin.stream property that provides a write-only interface to the response iterable.

stream

The response iterable as write-only stream.

class werkzeug.wrappers.CommonRequestDescriptorsMixin

A mixin for werkzeug.wrappers.BaseRequest" title="werkzeug.wrappers.BaseRequest subclasses. Request objects that mix this class in will automatically get descriptors for a couple of HTTP headers with automatic type conversion.

0.5 新版功能.

content_encoding

The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.

0.9 新版功能.

content_length

The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

content_md5
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)

0.9 新版功能.

content_type

The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.

date

The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.

max_forwards

The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.

mimetype

Like werkzeug.wrappers.CommonRequestDescriptorsMixin.content_type" title="werkzeug.wrappers.CommonRequestDescriptorsMixin.content_type but without parameters (eg, without charset, type etc.). For example if the content type is text/html; charset=utf-8 the mimetype would be 'text/html'.

mimetype_params

The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.

pragma

The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives.

referrer

The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).

class werkzeug.wrappers.CommonResponseDescriptorsMixin

A mixin for werkzeug.wrappers.BaseResponse" title="werkzeug.wrappers.BaseResponse subclasses. Response objects that mix this class in will automatically get descriptors for a couple of HTTP headers with automatic type conversion.

age

The Age response-header field conveys the sender’s estimate of the amount of time since the response (or its revalidation) was generated at the origin server.

Age values are non-negative decimal integers, representing time in seconds.

allow

The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The purpose of this field is strictly to inform the recipient of valid methods associated with the resource. An Allow header field MUST be present in a 405 (Method Not Allowed) response.

content_encoding

The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.

content_language

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

content_length

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

content_location

The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI.

content_md5

The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)

content_type

The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.

date

The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.

expires

The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache.

last_modified

The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.

location

The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource.

mimetype

The mimetype (content type without charset etc.)

mimetype_params

The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.

0.5 新版功能.

retry_after

The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client.

Time in seconds until expiration or date.

vary

The Vary field value indicates the set of request-header fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request without revalidation.

class werkzeug.wrappers.WWWAuthenticateMixin

Adds a werkzeug.wrappers.WWWAuthenticateMixin.www_authenticate" title="werkzeug.wrappers.WWWAuthenticateMixin.www_authenticate property to a response object.

www_authenticate

The WWW-Authenticate header in a parsed form.

class werkzeug.wrappers.UserAgentMixin

Adds a user_agent attribute to the request object which contains the parsed user agent of the browser that triggered the request as a UserAgent object.

user_agent

The current user agent.