ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Request / Response Objects The request and response objects wrap the WSGI environment or the returnvalue 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 responsephase. The [Request](# "werkzeug.wrappers.Request") class wraps the environ for easier access torequest variables (form data, request headers etc.). The [Response](# "werkzeug.wrappers.Response") on the other hand is a standard WSGI application thatyou 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 someprocessing: ~~~ 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 [Request](# "werkzeug.wrappers.Request") object providesa 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 theenvironment and start_response callable. ### Mutability and Reusability of Wrappers The implementation of the Werkzeug request and response objects are tryingto guard you from common pitfalls by disallowing certain things as much aspossible. This serves two purposes: high performance and avoiding ofpitfalls. For the request object the following rules apply: 1. The request object is immutable. Modifications are not supported bydefault, you may however replace the immutable attributes with mutableattributes if you need to modify it. 1. The request object may be shared in the same thread, but is not threadsafe itself. If you need to access it from multiple threads, uselocks around calls. 1. It's not possible to pickle the request object. For the response object the following rules apply: 1. The response object is mutable 1. The response object can be pickled or copied after freeze() wascalled. 1. Since Werkzeug 0.6 it's safe to use the same response object formultiple WSGI responses. 1. It's possible to create copies using copy.deepcopy. ### Base Wrappers These objects implement a common set of operations. They are missing fancyaddon functionality like user agent parsing or etag handling. These featuresare available by mixing in various mixin classes or using [Request](# "werkzeug.wrappers.Request") and[Response](# "werkzeug.wrappers.Response"). *class *werkzeug.wrappers.BaseRequest(*environ*, *populate_request=True*, *shallow=False*) Very basic request object. This does not implement advanced stuff likeentity tag parsing or cache controls. The request object is created withthe WSGI environment as first argument and will add itself to the WSGIenvironment as 'werkzeug.request' unless it's created withpopulate_request set to False. There are a couple of mixins available that add additional functionalityto the request object, there is also a class called Request whichsubclasses BaseRequest and all the important mixins. It's a good idea to create a custom subclass of the [BaseRequest](# "werkzeug.wrappers.BaseRequest")and add missing functionality either via mixins or direct implementation.Here an example for such subclasses: ~~~ from werkzeug.wrappers import BaseRequest, ETagRequestMixin class Request(BaseRequest, ETagRequestMixin): pass ~~~ Request objects are **read only**. As of 0.5 modifications are notallowed in any place. Unlike the lower level parsing functions therequest object will use immutable objects everywhere possible. Per default the request object will assume all the text data is utf-8encoded. Please refer to [the unicode chapter](#) for moredetails about customizing the behavior. Per default the request object will be added to the WSGIenvironment as werkzeug.request to support the debugging system.If you don't want that, set populate_request to False. If shallow is True the environment is initialized as shallowobject around the environ. Every operation that would modify theenviron in any way (such as consuming form data) raises an exceptionunless the shallow attribute is explicitly set to False. Thisis useful for middlewares where you don't want to consume the formdata by accident. A shallow request is not populated to the WSGIenvironment. 在 0.5 版更改: read-only mode was enforced by using immutables classes for alldata. environ The WSGI environment that the request object uses for data retrival. shallow True if this request object is shallow (does not modify [environ](# "werkzeug.wrappers.BaseRequest.environ")),False otherwise. _get_file_stream(*total_content_length*, *content_type*, *filename=None*, *content_length=None*) Called to get a stream for the file upload. This must provide a file-like class with read(), readline()and seek() methods that is both writeable and readable. The default implementation returns a temporary file if the totalcontent length is higher than 500KB. Because many browsers do notprovide a content length for the files only the total contentlength matters. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>total_content_length</strong> – the total content length of all thedata in the request combined. This valueis guaranteed to be there.</li><li><strong>content_type</strong> – the mimetype of the uploaded file.</li><li><strong>filename</strong> – the filename of the uploaded file. May be <cite>None</cite>.</li><li><strong>content_length</strong> – the length of this file. This value is usuallynot provided because webbrowsers do not providethis value.</li></ul></td></tr></tbody></table> access_route If a forwarded header exists this is a list of all ip addressesfrom the client ip to the last proxy server. *classmethod *application(*f*) Decorate a function as responder that accepts the request as firstargument. This works like the responder() decorator but thefunction is passed the request object as first argument and therequest object will be closed automatically: ~~~ @Request.application def my_wsgi_app(request): return Response('Hello World!') ~~~ | 参数: | **f** – the WSGI callable to decorate | |-----|-----| | 返回: | a new WSGI callable | args The parsed URL parameters. By default an[ImmutableMultiDict](# "werkzeug.datastructures.ImmutableMultiDict")is returned from this function. This can be changed by setting[parameter_storage_class](# "werkzeug.wrappers.BaseRequest.parameter_storage_class") to a different type. This mightbe necessary if the order of the form data is important. base_url Like [url](# "werkzeug.wrappers.BaseRequest.url") but without the querystring charset* = 'utf-8'* the charset for the request, defaults to utf-8 close() Closes associated resources of this request object. Thiscloses all file handles explicitly. You can also use the requestobject in a with statement with will automatically close it. 0.9 新版功能. cookies Read only access to the retrieved cookie values as dictionary. dict_storage_class the type to be used for dict values from the incoming WSGI environment.By default an[ImmutableTypeConversionDict](# "werkzeug.datastructures.ImmutableTypeConversionDict") is used(for example for [cookies](# "werkzeug.wrappers.BaseRequest.cookies")). 0.6 新版功能. ImmutableTypeConversionDict 的别名 disable_data_descriptor* = False* Indicates weather the data descriptor should be allowed to read andbuffer up the input stream. By default it's enabled. 0.9 新版功能. encoding_errors* = 'replace'* the error handling procedure for errors, defaults to ‘replace' files [MultiDict](# "werkzeug.datastructures.MultiDict") object containingall uploaded files. Each key in [files](# "werkzeug.wrappers.BaseRequest.files") is the name from the<inputtype="file"name="">. Each value in [files](# "werkzeug.wrappers.BaseRequest.files") is aWerkzeug [FileStorage](# "werkzeug.datastructures.FileStorage") object. Note that [files](# "werkzeug.wrappers.BaseRequest.files") will only contain data if the request method wasPOST, PUT or PATCH and the <form> that posted to the request hadenctype="multipart/form-data". It will be empty otherwise. See the [MultiDict](# "werkzeug.datastructures.MultiDict") /[FileStorage](# "werkzeug.datastructures.FileStorage") documentation formore details about the used data structure. form The form parameters. By default an[ImmutableMultiDict](# "werkzeug.datastructures.ImmutableMultiDict")is returned from this function. This can be changed by setting[parameter_storage_class](# "werkzeug.wrappers.BaseRequest.parameter_storage_class") to a different type. This mightbe necessary if the order of the form data is important. form_data_parser_class The form data parser that shoud be used. Can be replaced to customizethe form date parsing. FormDataParser 的别名 *classmethod *from_values(**args*, ***kwargs*) Create a new request object based on the values provided. Ifenviron is given missing values are filled from there. This method isuseful for small scripts when you need to simulate a request from an URL.Do not use this method for unittesting, there is a full featured clientobject (Client) that allows to create multipart requests,support for cookies etc. This accepts the same options as theEnvironBuilder. 在 0.5 版更改: This method now accepts the same arguments asEnvironBuilder. Because of this theenviron parameter is now called environ_overrides. | 返回: | request object | |-----|-----| full_path Requested path as unicode, including the query string. get_data(*cache=True*, *as_text=False*, *parse_form_data=False*) This reads the buffered incoming data from the client into onebytestring. By default this is cached but that behavior can bechanged by setting cache to False. Usually it's a bad idea to call this method without checking thecontent length first as a client could send dozens of megabytes or moreto cause memory problems on the server. Note that if the form data was already parsed this method will notreturn anything as form data parsing does not cache the data likethis method does. To implicitly invoke form data parsing functionset parse_form_data to True. When this is done the return valueof this method will be an empty string if the form parser handlesthe data. This generally is not necessary as if the whole data iscached (which is the default) the form parser will used the cacheddata to parse the form data. Please be generally aware of checkingthe content length first in any case before calling this methodto avoid exhausting server memory. If as_text is set to True the return value will be a decodedunicode string. 0.9 新版功能. headers The headers from the WSGI environ as immutable[EnvironHeaders](# "werkzeug.datastructures.EnvironHeaders"). host Just the host including the port if available. host_url Just the host with scheme. is_multiprocess boolean that is True if the application is served bya WSGI server that spawns multiple processes. is_multithread boolean that is True if the application is served bya multithreaded WSGI server. is_run_once boolean that is True if the application will be executed onlyonce in a process lifetime. This is the case for CGI for example,but it's not guaranteed that the exeuction only happens one time. is_secure True if the request is secure. is_xhr True if the request was triggered via a JavaScript XMLHttpRequest.This only works with libraries that support the X-Requested-Withheader and set it to “XMLHttpRequest”. Libraries that do that areprototype, jQuery and Mochikit and probably some more. list_storage_class the type to be used for list values from the incoming WSGI environment.By default an [ImmutableList](# "werkzeug.datastructures.ImmutableList") is used(for example for access_list). 0.6 新版功能. ImmutableList 的别名 make_form_data_parser() Creates the form data parser. Instanciates the[form_data_parser_class](# "werkzeug.wrappers.BaseRequest.form_data_parser_class") with some parameters. 0.8 新版功能. max_content_length* = None* the maximum content length. This is forwarded to the form dataparsing function (parse_form_data()). When set and the[form](# "werkzeug.wrappers.BaseRequest.form") or [files](# "werkzeug.wrappers.BaseRequest.files") attribute is accessed and theparsing fails because more than the specified value is transmitteda [RequestEntityTooLarge](# "werkzeug.exceptions.RequestEntityTooLarge") exception is raised. Have a look at [*Dealing with Request Data*](#) for more details. 0.5 新版功能. max_form_memory_size* = None* the maximum form field size. This is forwarded to the form dataparsing function (parse_form_data()). When set and the[form](# "werkzeug.wrappers.BaseRequest.form") or [files](# "werkzeug.wrappers.BaseRequest.files") attribute is accessed and thedata in memory for post data is longer than the specified value a[RequestEntityTooLarge](# "werkzeug.exceptions.RequestEntityTooLarge") exception is raised. Have a look at [*Dealing with Request Data*](#) for more details. 0.5 新版功能. method The transmission method. (For example 'GET' or 'POST'). parameter_storage_class the class to use for args and form. The default is an[ImmutableMultiDict](# "werkzeug.datastructures.ImmutableMultiDict") which supportsmultiple values per key. alternatively it makes sense to use an[ImmutableOrderedMultiDict](# "werkzeug.datastructures.ImmutableOrderedMultiDict") whichpreserves order or a [ImmutableDict](# "werkzeug.datastructures.ImmutableDict")which is the fastest but only remembers the last key. It is alsopossible to use mutable structures, but this is not recommended. 0.6 新版功能. ImmutableMultiDict 的别名 path Requested path as unicode. This works a bit like the regular pathinfo in the WSGI environment but will always include a leading slash,even if the URL root is accessed. query_string The URL parameters as raw bytestring. remote_addr The remote address of the client. remote_user If the server supports user authentication, and the script isprotected, this attribute contains the username the user hasauthenticated as. scheme URL scheme (http or https). 0.7 新版功能. script_root The root path of the script without the trailing slash. stream The stream to read incoming data from. Unlike input_streamthis stream is properly guarded that you can't accidentally read pastthe length of the input. Werkzeug will internally always refer tothis stream to read data which makes it possible to wrap thisobject with a stream that does filtering. 在 0.9 版更改: This stream is now always available but might be consumed by theform parser later on. Previously the stream was only set if noparsing happened. trusted_hosts* = None* Optionally a list of hosts that is trusted by this request. By defaultall hosts are trusted which means that whatever the client sends thehost is will be accepted. This is the recommended setup as a webservershould manually be set up to not route invalid hosts to the application. 0.9 新版功能. url The reconstructed current URL url_charset The charset that is assumed for URLs. Defaults to the valueof [charset](# "werkzeug.wrappers.BaseRequest.charset"). 0.6 新版功能. url_root The full URL root (with hostname), this is the application root. values Combined multi dict for [args](# "werkzeug.wrappers.BaseRequest.args") and [form](# "werkzeug.wrappers.BaseRequest.form"). want_form_data_parsed Returns True if the request method carries content. As ofWerkzeug 0.9 this will be the case if a content type is transmitted. 0.8 新版功能. *class *werkzeug.wrappers.BaseResponse(*response=None*, *status=None*, *headers=None*, *mimetype=None*, *content_type=None*, *direct_passthrough=False*) Base response class. The most important fact about a response objectis that it's a regular WSGI application. It's initialized with a coupleof response parameters (headers, body, status code etc.) and will start avalid WSGI response when called with the environ and start responsecallable. Because it's a WSGI application itself processing usually ends before theactual response is sent to the server. This helps debugging systemsbecause they can catch all the exceptions before responses are started. Here a small example WSGI application that takes advantage of theresponse objects: ~~~ from werkzeug.wrappers import BaseResponse as Response def index(): return Response('Index page') def application(environ, start_response): path = environ.get('PATH_INFO') or '/' if path == '/': response = index() else: response = Response('Not Found', status=404) return response(environ, start_response) ~~~ Like [BaseRequest](# "werkzeug.wrappers.BaseRequest") which object is lacking a lot of functionalityimplemented in mixins. This gives you a better control about the actualAPI of your response objects, so you can create subclasses and add customfunctionality. A full featured response object is available as[Response](# "werkzeug.wrappers.Response") which implements a couple of useful mixins. To enforce a new type of already existing responses you can use the[force_type()](# "werkzeug.wrappers.BaseResponse.force_type") method. This is useful if you're working with differentsubclasses of response objects and you want to post process them with aknow interface. Per default the request object will assume all the text data is utf-8encoded. Please refer to [the unicode chapter](#) for moredetails about customizing the behavior. Response can be any kind of iterable or string. If it's a string it'sconsidered being an iterable with one item which is the string passed.Headers can be a list of tuples or a[Headers](# "werkzeug.datastructures.Headers") object. Special note for mimetype and content_type: For most mime typesmimetype and content_type work the same, the difference affectsonly ‘text' mimetypes. If the mimetype passed with mimetype is amimetype starting with text/, the charset parameter of the responseobject is appended to it. In contrast the content_type parameter isalways added as header unmodified. 在 0.5 版更改: the direct_passthrough parameter was added. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>response</strong> – a string or response iterable.</li><li><strong>status</strong> – a string with a status or an integer with the status code.</li><li><strong>headers</strong> – a list of headers or a<a class="reference internal" href="datastructures.html#werkzeug.datastructures.Headers" title="werkzeug.datastructures.Headers"><tt class="xref py py-class docutils literal"><span class="pre">Headers</span></tt></a> object.</li><li><strong>mimetype</strong> – the mimetype for the request. See notice above.</li><li><strong>content_type</strong> – the content type for the request. See notice above.</li><li><strong>direct_passthrough</strong> – if set to <cite>True</cite> <a class="reference internal" href="#werkzeug.wrappers.BaseResponse.iter_encoded" title="werkzeug.wrappers.BaseResponse.iter_encoded"><tt class="xref py py-meth docutils literal"><span class="pre">iter_encoded()</span></tt></a> is notcalled before iteration which makes itpossible to pass special iterators thoughunchanged (see <tt class="xref py py-func docutils literal"><span class="pre">wrap_file()</span></tt> for moredetails.)</li></ul></td></tr></tbody></table> response The application iterator. If constructed from a string this will be alist, otherwise the object provided as application iterator. (The firstargument passed to [BaseResponse](# "werkzeug.wrappers.BaseResponse")) headers A Headers object representing the response headers. status_code The response status as integer. direct_passthrough If direct_passthrough=True was passed to the response object or ifthis attribute was set to True before using the response object asWSGI application, the wrapped iterator is returned unchanged. Thismakes it possible to pass a special wsgi.file_wrapper to the responseobject. See wrap_file() for more details. __call__(*environ*, *start_response*) Process this response as WSGI application. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first simple"><li><strong>environ</strong> – the WSGI environment.</li><li><strong>start_response</strong> – the response callable provided by the WSGIserver.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">an application iterator</p></td></tr></tbody></table> _ensure_sequence(*mutable=False*) This method can be called by methods that need a sequence. Ifmutable is true, it will also ensure that the response sequenceis a standard Python list. 0.6 新版功能. autocorrect_location_header* = True* Should this response object correct the location header to be RFCconformant? This is true by default. 0.8 新版功能. automatically_set_content_length* = True* Should this response object automatically set the content-lengthheader if possible? This is true by default. 0.8 新版功能. calculate_content_length() Returns the content length if available or None otherwise. call_on_close(*func*) Adds a function to the internal list of functions that shouldbe called as part of closing down the response. Since 0.7 thisfunction also returns the function that was passed so that thiscan be used as a decorator. 0.6 新版功能. charset* = 'utf-8'* the charset of the response. close() Close the wrapped response if possible. You can also use the objectin a with statement which will automatically close it. 0.9 新版功能: Can now be used in a with statement. data A descriptor that calls [get_data()](# "werkzeug.wrappers.BaseResponse.get_data") and [set_data()](# "werkzeug.wrappers.BaseResponse.set_data"). Thisshould not be used and will eventually get deprecated. default_mimetype* = 'text/plain'* the default mimetype if none is provided. default_status* = 200* the default status if none is provided. delete_cookie(*key*, *path='/'*, *domain=None*) Delete a cookie. Fails silently if key doesn't exist. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key (name) of the cookie to be deleted.</li><li><strong>path</strong> – if the cookie that should be deleted was limited to apath, the path has to be defined here.</li><li><strong>domain</strong> – if the cookie that should be deleted was limited to adomain, that domain has to be defined here.</li></ul></td></tr></tbody></table> *classmethod *force_type(*response*, *environ=None*) Enforce that the WSGI response is a response object of the currenttype. Werkzeug will use the [BaseResponse](# "werkzeug.wrappers.BaseResponse") internally in manysituations like the exceptions. If you call get_response() on anexception you will get back a regular [BaseResponse](# "werkzeug.wrappers.BaseResponse") object, evenif you are using a custom subclass. This method can enforce a given response type, and it will alsoconvert arbitrary WSGI callables into response objects if an environis provided: ~~~ # convert a Werkzeug response object into an instance of the # MyResponseClass subclass. response = MyResponseClass.force_type(response) # convert any WSGI application into a response object response = MyResponseClass.force_type(response, environ) ~~~ This is especially useful if you want to post-process responses inthe main dispatcher and use functionality provided by your subclass. Keep in mind that this will modify response objects in place ifpossible! <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first simple"><li><strong>response</strong> – a response object or wsgi application.</li><li><strong>environ</strong> – a WSGI environment object.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">a response object.</p></td></tr></tbody></table> freeze() Call this method if you want to make your response object ready forbeing pickled. This buffers the generator if there is one. It willalso set the Content-Length header to the length of the body. 在 0.6 版更改: The Content-Length header is now set. *classmethod *from_app(*app*, *environ*, *buffered=False*) Create a new response object from an application output. Thisworks best if you pass it an application that returns a generator allthe time. Sometimes applications may use the write() callablereturned by the start_response function. This tries to resolve suchedge cases automatically. But if you don't get the expected outputyou should set buffered to True which enforces buffering. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first simple"><li><strong>app</strong> – the WSGI application to execute.</li><li><strong>environ</strong> – the WSGI environment to execute against.</li><li><strong>buffered</strong> – set to <cite>True</cite> to enforce buffering.</li></ul></td></tr><tr class="field-even field"><th class="field-name">返回:</th><td class="field-body"><p class="first last">a response object.</p></td></tr></tbody></table> get_app_iter(*environ*) Returns the application iterator for the given environ. Dependingon the request method and the current status code the return valuemight be an empty response rather than the one from the response. If the request method is HEAD or the status code is in a rangewhere the HTTP specification requires an empty response, an emptyiterable is returned. 0.6 新版功能. | 参数: | **environ** – the WSGI environment of the request. | |-----|-----| | 返回: | a response iterable. | get_data(*as_text=False*) The string representation of the request body. Whenever you callthis property the request iterable is encoded and flattened. Thiscan lead to unwanted behavior if you stream big data. This behavior can be disabled by setting[implicit_sequence_conversion](# "werkzeug.wrappers.BaseResponse.implicit_sequence_conversion") to False. If as_text is set to True the return value will be a decodedunicode string. 0.9 新版功能. get_wsgi_headers(*environ*) This is automatically called right before the response is startedand returns headers modified for the given environment. It returns acopy of the headers from the response with some modifications appliedif necessary. For example the location header (if present) is joined with the rootURL of the environment. Also the content length is automatically setto zero here for certain status codes. 在 0.6 版更改: Previously that function was called fix_headers and modifiedthe response object in place. Also since 0.6, IRIs in locationand content-location headers are handled properly. Also starting with 0.6, Werkzeug will attempt to set the contentlength if it is able to figure it out on its own. This is thecase if all the strings in the response iterable are alreadyencoded and the iterable is buffered. | 参数: | **environ** – the WSGI environment of the request. | |-----|-----| | 返回: | returns a new [Headers](# "werkzeug.datastructures.Headers")object. | get_wsgi_response(*environ*) Returns the final WSGI response as tuple. The first item inthe tuple is the application iterator, the second the status andthe third the list of headers. The response returned is createdspecially for the given environment. For example if the requestmethod in the WSGI environment is 'HEAD' the response willbe empty and only the headers and status code will be present. 0.6 新版功能. | 参数: | **environ** – the WSGI environment of the request. | |-----|-----| | 返回: | an (app_iter,status,headers) tuple. | implicit_sequence_conversion* = True* if set to False accessing properties on the response object willnot try to consume the response iterator and convert it into a list. 0.6.2 新版功能: That attribute was previously called implicit_seqence_conversion.(Notice the typo). If you did use this feature, you have to adaptyour code to the name change. is_sequence If the iterator is buffered, this property will be True. Aresponse object will consider an iterator to be buffered if theresponse attribute is a list or tuple. 0.6 新版功能. is_streamed If the response is streamed (the response is not an iterable witha length information) this property is True. In this case streamedmeans that there is no information about the number of iterations.This is usually True if a generator is passed to the response object. This is useful for checking before applying some sort of postfiltering that should not take place for streamed responses. iter_encoded() Iter the response encoded with the encoding of the response.If the response object is invoked as WSGI application the returnvalue of this method is used as application iterator unless[direct_passthrough](# "werkzeug.wrappers.BaseResponse.direct_passthrough") was activated. make_sequence() Converts the response iterator in a list. By default this happensautomatically if required. If implicit_sequence_conversion isdisabled, this method is not automatically called and some propertiesmight raise exceptions. This also encodes all the items. 0.6 新版功能. set_cookie(*key*, *value=''*, *max_age=None*, *expires=None*, *path='/'*, *domain=None*, *secure=None*, *httponly=False*) Sets a cookie. The parameters are the same as in the cookie Morselobject in the Python standard library but it accepts unicode data, too. <table class="docutils field-list" frame="void" rules="none"><col class="field-name"/><col class="field-body"/><tbody valign="top"><tr class="field-odd field"><th class="field-name">参数:</th><td class="field-body"><ul class="first last simple"><li><strong>key</strong> – the key (name) of the cookie to be set.</li><li><strong>value</strong> – the value of the cookie.</li><li><strong>max_age</strong> – should be a number of seconds, or <cite>None</cite> (default) ifthe cookie should last only as long as the client'sbrowser session.</li><li><strong>expires</strong> – should be a <cite>datetime</cite> object or UNIX timestamp.</li><li><strong>domain</strong> – if you want to set a cross-domain cookie. For example,<tt class="docutils literal"><span class="pre">domain=".example.com"</span></tt> will set a cookie that isreadable by the domain <tt class="docutils literal"><span class="pre">www.example.com</span></tt>,<tt class="docutils literal"><span class="pre">foo.example.com</span></tt> etc. Otherwise, a cookie will onlybe readable by the domain that set it.</li><li><strong>path</strong> – limits the cookie to a given path, per default it willspan the whole domain.</li></ul></td></tr></tbody></table> set_data(*value*) Sets a new string as response. The value set must either by aunicode or bytestring. If a unicode string is set it's encodedautomatically to the charset of the response (utf-8 by default). 0.9 新版功能. status The HTTP Status code status_code The HTTP Status code as number ### Mixin Classes Werkzeug also provides helper mixins for various HTTP related functionalitysuch as etags, cache control, user agents etc. When subclassing you canmix those classes in to extend the functionality of the [BaseRequest](# "werkzeug.wrappers.BaseRequest")or [BaseResponse](# "werkzeug.wrappers.BaseResponse") object. Here a small example for a request objectthat parses accept headers: ~~~ from werkzeug.wrappers import AcceptMixin, BaseRequest class Request(BaseRequest, AcceptMixin): pass ~~~ The [Request](# "werkzeug.wrappers.Request") and [Response](# "werkzeug.wrappers.Response") classes subclass the [BaseRequest](# "werkzeug.wrappers.BaseRequest")and [BaseResponse](# "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: - [AcceptMixin](# "werkzeug.wrappers.AcceptMixin") for accept header parsing - [ETagRequestMixin](# "werkzeug.wrappers.ETagRequestMixin") for etag and cache control handling - [UserAgentMixin](# "werkzeug.wrappers.UserAgentMixin") for user agent introspection - [AuthorizationMixin](# "werkzeug.wrappers.AuthorizationMixin") for http auth handling - [CommonRequestDescriptorsMixin](# "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: - [ETagResponseMixin](# "werkzeug.wrappers.ETagResponseMixin") for etag and cache control handling - [ResponseStreamMixin](# "werkzeug.wrappers.ResponseStreamMixin") to add support for the stream property - [CommonResponseDescriptorsMixin](# "werkzeug.wrappers.CommonResponseDescriptorsMixin") for various HTTP descriptors - [WWWAuthenticateMixin](# "werkzeug.wrappers.WWWAuthenticateMixin") for HTTP authentication support *class *werkzeug.wrappers.AcceptMixin A mixin for classes with an environ attributeto get all the HTTP accept headers as[Accept](# "werkzeug.datastructures.Accept") objects (or subclassesthereof). accept_charsets List of charsets this client supports as[CharsetAccept](# "werkzeug.datastructures.CharsetAccept") object. accept_encodings List of encodings this client accepts. Encodings in a HTTP termare compression encodings such as gzip. For charsets have a look ataccept_charset. accept_languages List of languages this client accepts as[LanguageAccept](# "werkzeug.datastructures.LanguageAccept") object. accept_mimetypes List of mimetypes this client supports as[MIMEAccept](# "werkzeug.datastructures.MIMEAccept") object. *class *werkzeug.wrappers.AuthorizationMixin Adds an [authorization](# "werkzeug.wrappers.AuthorizationMixin.authorization") property that represents the parsedvalue of the Authorization header as[Authorization](# "werkzeug.datastructures.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 witha WSGI environment available as [environ](# "werkzeug.wrappers.BaseRequest.environ"). This notonly provides access to etags but also to the cache control header. cache_control A [RequestCacheControl](# "werkzeug.datastructures.RequestCacheControl") objectfor the incoming cache control headers. if_match An object containing all the etags in the If-Match header. | 返回类型: | [ETags](# "werkzeug.datastructures.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](# "werkzeug.datastructures.ETags") | |-----|-----| if_range The parsed If-Range header. 0.7 新版功能. | 返回类型: | [IfRange](# "werkzeug.datastructures.IfRange") | |-----|-----| if_unmodified_since The parsed If-Unmodified-Since header as datetime object. range The parsed Range header. 0.7 新版功能. | 返回类型: | [Range](# "werkzeug.datastructures.Range") | |-----|-----| *class *werkzeug.wrappers.ETagResponseMixin Adds extra functionality to a response object for etag and cachehandling. This mixin requires an object with at least a headersobject that implements a dict like interface similar to[Headers](# "werkzeug.datastructures.Headers"). If you want the [freeze()](# "werkzeug.wrappers.ETagResponseMixin.freeze") method to automatically add an etag, youhave to mixin this method before the response base class. The defaultresponse class does not do that. accept_ranges The Accept-Ranges header. Even though the name would indicatethat 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 specifydirectives that MUST be obeyed by all caching mechanisms along therequest/response chain. content_range The Content-Range header as[ContentRange](# "werkzeug.datastructures.ContentRange") object. Even if theheader is not set it wil provide such an object for easiermanipulation. 0.7 新版功能. freeze(*no_etag=False*) Call this method if you want to make your response object ready forpickeling. This buffers the generator if there is one. This alsosets the etag unless no_etag is set to True. get_etag() Return a tuple in the form (etag,is_weak). If there is noETag the return value is (None,None). make_conditional(*request_or_environ*) Make the response conditional to the request. This method worksbest if an etag was defined for the response already. The add_etagmethod can be used to do that. If called without etag just the dateheader is set. This does nothing if the request method in the request or environ isanything but GET or HEAD. It does not remove the body of the response because that's somethingthe __call__() function does for us automatically. Returns self so that you can do returnresp.make_conditional(req)but modifies the object in-place. | 参数: | **request_or_environ** – a request object or WSGI environment to beused to make the response conditionalagainst. | |-----|-----| set_etag(*etag*, *weak=False*) Set the etag, and override the old one if there was one. *class *werkzeug.wrappers.ResponseStreamMixin Mixin for [BaseRequest](# "werkzeug.wrappers.BaseRequest") subclasses. Classes that inherit fromthis mixin will automatically get a [stream](# "werkzeug.wrappers.ResponseStreamMixin.stream") property that providesa write-only interface to the response iterable. stream The response iterable as write-only stream. *class *werkzeug.wrappers.CommonRequestDescriptorsMixin A mixin for [BaseRequest](# "werkzeug.wrappers.BaseRequest") subclasses. Request objects thatmix this class in will automatically get descriptors for a couple ofHTTP headers with automatic type conversion. 0.5 新版功能. content_encoding The Content-Encoding entity-header field is used as a modifier to themedia-type. When present, its value indicates what additional contentcodings have been applied to the entity-body, and thus what decodingmechanisms must be applied in order to obtain the media-typereferenced by the Content-Type header field. 0.9 新版功能. content_length The Content-Length entity-header field indicates the size of theentity-body in bytes or, in the case of the HEAD method, the size ofthe entity-body that would have been sent had the request been aGET. content_md5> The Content-MD5 entity-header field, as defined in RFC 1864, is anMD5 digest of the entity-body for the purpose of providing anend-to-end message integrity check (MIC) of the entity-body. (Note:a MIC is good for detecting accidental modification of theentity-body in transit, but is not proof against malicious attacks.) 0.9 新版功能. content_type The Content-Type entity-header field indicates the media type ofthe entity-body sent to the recipient or, in the case of the HEADmethod, the media type that would have been sent had the requestbeen a GET. date The Date general-header field represents the date and time at whichthe message was originated, having the same semantics as orig-datein RFC 822. max_forwards The Max-Forwards request-header field provides a mechanism with theTRACE and OPTIONS methods to limit the number of proxies or gatewaysthat can forward the request to the next inbound server. mimetype Like [content_type](# "werkzeug.wrappers.CommonRequestDescriptorsMixin.content_type") but without parameters (eg, withoutcharset, type etc.). For example if the contenttype is text/html;charset=utf-8 the mimetype would be'text/html'. mimetype_params The mimetype parameters as dict. For example if the contenttype is text/html;charset=utf-8 the params would be{'charset':'utf-8'}. pragma The Pragma general-header field is used to includeimplementation-specific directives that might apply to any recipientalong the request/response chain. All pragma directives specifyoptional behavior from the viewpoint of the protocol; however, somesystems 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 whichthe Request-URI was obtained (the “referrer”, although the headerfield is misspelled). *class *werkzeug.wrappers.CommonResponseDescriptorsMixin A mixin for [BaseResponse](# "werkzeug.wrappers.BaseResponse") subclasses. Response objects thatmix this class in will automatically get descriptors for a couple ofHTTP headers with automatic type conversion. age The Age response-header field conveys the sender's estimate of theamount of time since the response (or its revalidation) wasgenerated at the origin server. Age values are non-negative decimal integers, representing time inseconds. allow The Allow entity-header field lists the set of methods supportedby the resource identified by the Request-URI. The purpose of thisfield is strictly to inform the recipient of valid methodsassociated with the resource. An Allow header field MUST bepresent in a 405 (Method Not Allowed) response. content_encoding The Content-Encoding entity-header field is used as a modifier to themedia-type. When present, its value indicates what additional contentcodings have been applied to the entity-body, and thus what decodingmechanisms must be applied in order to obtain the media-typereferenced by the Content-Type header field. content_language The Content-Language entity-header field describes the naturallanguage(s) of the intended audience for the enclosed entity. Notethat this might not be equivalent to all the languages used withinthe entity-body. content_length The Content-Length entity-header field indicates the size of theentity-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 wouldhave been sent had the request been a GET. content_location The Content-Location entity-header field MAY be used to supply theresource location for the entity enclosed in the message when thatentity is accessible from a location separate from the requestedresource's URI. content_md5 The Content-MD5 entity-header field, as defined in RFC 1864, is anMD5 digest of the entity-body for the purpose of providing anend-to-end message integrity check (MIC) of the entity-body. (Note:a MIC is good for detecting accidental modification of theentity-body in transit, but is not proof against malicious attacks.) content_type The Content-Type entity-header field indicates the media type of theentity-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 whichthe message was originated, having the same semantics as orig-datein RFC 822. expires The Expires entity-header field gives the date/time after which theresponse is considered stale. A stale cache entry may not normally bereturned by a cache. last_modified The Last-Modified entity-header field indicates the date and time atwhich the origin server believes the variant was last modified. location The Location response-header field is used to redirect the recipientto a location other than the Request-URI for completion of the requestor identification of a new resource. mimetype The mimetype (content type without charset etc.) mimetype_params The mimetype parameters as dict. For example if the contenttype 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 (ServiceUnavailable) response to indicate how long the service is expectedto 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 thatfully determines, while the response is fresh, whether a cache ispermitted to use the response to reply to a subsequent requestwithout revalidation. *class *werkzeug.wrappers.WWWAuthenticateMixin Adds a [www_authenticate](# "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 theparsed user agent of the browser that triggered the request as a[UserAgent](# "werkzeug.useragents.UserAgent") object. user_agent The current user agent.