WSGI Helpers

最后更新于:2022-04-01 04:07:25

# WSGI Helpers The following classes and functions are designed to make working withthe WSGI specification easier or operate on the WSGI layer. All thefunctionality from this module is available on the high-level[*Request/Response classes*](#). ### Iterator / Stream Helpers These classes and functions simplify working with the WSGI applicationiterator and the input stream. *class *werkzeug.wsgi.ClosingIterator(*iterable*, *callbacks=None*) The WSGI specification requires that all middlewares and gatewaysrespect the close callback of an iterator. Because it is useful to addanother close action to a returned iterator and adding a custom iteratoris a boring task this class can be used for that: ~~~ return ClosingIterator(app(environ, start_response), [cleanup_session, cleanup_locals]) ~~~ If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objectsand finishes the processing if the response is started: ~~~ try: return response(environ, start_response) finally: cleanup_session() cleanup_locals() ~~~ *class *werkzeug.wsgi.FileWrapper(*file*, *buffer_size=8192*) This class can be used to convert a file-like object intoan iterable. It yields buffer_size blocks until the file is fullyread. You should not use this class directly but rather use the[wrap_file()](# "werkzeug.wsgi.wrap_file") function that uses the WSGI server's file wrappersupport if it's available. 0.5 新版功能. If you're using this object together with a BaseResponse you haveto use the direct_passthrough mode. <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>file</strong> – a <tt class="xref py py-class docutils literal"><span class="pre">file</span></tt>-like object with a <tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt> method.</li><li><strong>buffer_size</strong> – number of bytes for one iteration.</li></ul></td></tr></tbody></table> *class *werkzeug.wsgi.LimitedStream(*stream*, *limit*) Wraps a stream so that it doesn't read more than n bytes. If thestream is exhausted and the caller tries to get more bytes from it[on_exhausted()](# "werkzeug.wsgi.LimitedStream.on_exhausted") is called which by default returns an emptystring. The return value of that function is forwardedto the reader function. So if it returns an empty string[read()](# "werkzeug.wsgi.LimitedStream.read") will return an empty string as well. The limit however must never be higher than what the stream canoutput. Otherwise [readlines()](# "werkzeug.wsgi.LimitedStream.readlines") will try to read past thelimit. Note on WSGI compliance calls to [readline()](# "werkzeug.wsgi.LimitedStream.readline") and [readlines()](# "werkzeug.wsgi.LimitedStream.readlines") are notWSGI compliant because it passes a size argument to thereadline methods. Unfortunately the WSGI PEP is not safelyimplementable without a size argument to [readline()](# "werkzeug.wsgi.LimitedStream.readline")because there is no EOF marker in the stream. As a resultof that the use of [readline()](# "werkzeug.wsgi.LimitedStream.readline") is discouraged. For the same reason iterating over the [LimitedStream](# "werkzeug.wsgi.LimitedStream")is not portable. It internally calls [readline()](# "werkzeug.wsgi.LimitedStream.readline"). We strongly suggest using [read()](# "werkzeug.wsgi.LimitedStream.read") only or using the[make_line_iter()](# "werkzeug.wsgi.make_line_iter") which safely iterates line-basedover a WSGI input stream. <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>stream</strong> – the stream to wrap.</li><li><strong>limit</strong> – the limit for the stream, must not be longer thanwhat the string can provide if the stream does notend with <cite>EOF</cite> (like <cite>wsgi.input</cite>)</li></ul></td></tr></tbody></table> exhaust(*chunk_size=65536*) Exhaust the stream. This consumes all the data left until thelimit is reached. | 参数: | **chunk_size** – the size for a chunk. It will read the chunkuntil the stream is exhausted and throw awaythe results. | |-----|-----| is_exhausted If the stream is exhausted this attribute is True. on_disconnect() What should happen if a disconnect is detected? The returnvalue of this function is returned from read functions in casethe client went away. By default a[ClientDisconnected](# "werkzeug.exceptions.ClientDisconnected") exception is raised. on_exhausted() This is called when the stream tries to read past the limit.The return value of this function is returned from the readingfunction. read(*size=None*) Read size bytes or if size is not provided everything is read. | 参数: | **size** – the number of bytes read. | |-----|-----| readline(*size=None*) Reads one line from the stream. readlines(*size=None*) Reads a file into a list of strings. It calls [readline()](# "werkzeug.wsgi.LimitedStream.readline")until the file is read to the end. It does support the optionalsize argument if the underlaying stream supports it forreadline. tell() Returns the position of the stream. 0.9 新版功能. werkzeug.wsgi.make_line_iter(*stream*, *limit=None*, *buffer_size=10240*) Safely iterates line-based over an input stream. If the input streamis not a [LimitedStream](# "werkzeug.wsgi.LimitedStream") the limit parameter is mandatory. This uses the stream's read() method internally as oppositeto the readline() method that is unsafe and can only be usedin violation of the WSGI specification. The same problem applies to the__iter__ function of the input stream which calls readline()without arguments. If you need line-by-line processing it's strongly recommended to iterateover the input stream using this helper function. 在 0.8 版更改: This function now ensures that the limit was reached. 0.9 新版功能: added support for iterators as input stream. <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>stream</strong> – the stream or iterate to iterate over.</li><li><strong>limit</strong> – the limit in bytes for the stream. (Usuallycontent length. Not necessary if the <cite>stream</cite>is a <a class="reference internal" href="#werkzeug.wsgi.LimitedStream" title="werkzeug.wsgi.LimitedStream"><tt class="xref py py-class docutils literal"><span class="pre">LimitedStream</span></tt></a>.</li><li><strong>buffer_size</strong> – The optional buffer size.</li></ul></td></tr></tbody></table> werkzeug.wsgi.make_chunk_iter(*stream*, *separator*, *limit=None*, *buffer_size=10240*) Works like [make_line_iter()](# "werkzeug.wsgi.make_line_iter") but accepts a separatorwhich divides chunks. If you want newline based processingyou should use [make_line_iter()](# "werkzeug.wsgi.make_line_iter") instead as itsupports arbitrary newline markers. 0.8 新版功能. 0.9 新版功能: added support for iterators as input stream. <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>stream</strong> – the stream or iterate to iterate over.</li><li><strong>separator</strong> – the separator that divides chunks.</li><li><strong>limit</strong> – the limit in bytes for the stream. (Usuallycontent length. Not necessary if the <cite>stream</cite>is otherwise already limited).</li><li><strong>buffer_size</strong> – The optional buffer size.</li></ul></td></tr></tbody></table> werkzeug.wsgi.wrap_file(*environ*, *file*, *buffer_size=8192*) Wraps a file. This uses the WSGI server's file wrapper if availableor otherwise the generic [FileWrapper](# "werkzeug.wsgi.FileWrapper"). 0.5 新版功能. If the file wrapper from the WSGI server is used it's important to notiterate over it from inside the application but to pass it throughunchanged. If you want to pass out a file wrapper inside a responseobject you have to set direct_passthrough to True. More information about file wrappers are available in [**PEP 333**](http://www.python.org/dev/peps/pep-0333) [http://www.python.org/dev/peps/pep-0333]. <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>file</strong> – a <tt class="xref py py-class docutils literal"><span class="pre">file</span></tt>-like object with a <tt class="xref py py-meth docutils literal"><span class="pre">read()</span></tt> method.</li><li><strong>buffer_size</strong> – number of bytes for one iteration.</li></ul></td></tr></tbody></table> ### Environ Helpers These functions operate on the WSGI environment. They extract usefulinformation or perform common manipulations: werkzeug.wsgi.get_host(*environ*, *trusted_hosts=None*) Return the real host for the given WSGI environment. This takes careof the X-Forwarded-Host header. Optionally it verifies that the hostis in a list of trusted hosts. If the host is not in there it will raisea [SecurityError](# "werkzeug.exceptions.SecurityError"). <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>environ</strong> – the WSGI environment to get the host of.</li><li><strong>trusted_hosts</strong> – a list of trusted hosts, see <a class="reference internal" href="#werkzeug.wsgi.host_is_trusted" title="werkzeug.wsgi.host_is_trusted"><tt class="xref py py-func docutils literal"><span class="pre">host_is_trusted()</span></tt></a>for more information.</li></ul></td></tr></tbody></table> werkzeug.wsgi.get_content_length(*environ*) Returns the content length from the WSGI environment asinteger. If it's not available None is returned. 0.9 新版功能. | 参数: | **environ** – the WSGI environ to fetch the content length from. | |-----|-----| werkzeug.wsgi.get_input_stream(*environ*, *safe_fallback=True*) Returns the input stream from the WSGI environment and wraps itin the most sensible way possible. The stream returned is not theraw WSGI stream in most cases but one that is safe to read fromwithout taking into account the content length. 0.9 新版功能. <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>environ</strong> – the WSGI environ to fetch the stream from.</li><li><strong>safe</strong> – indicates weather the function should use an emptystream as safe fallback or just return the originalWSGI input stream if it can't wrap it safely. Thedefault is to return an empty string in those cases.</li></ul></td></tr></tbody></table> werkzeug.wsgi.get_current_url(*environ*, *root_only=False*, *strip_querystring=False*, *host_only=False*, *trusted_hosts=None*) A handy helper function that recreates the full URL for the currentrequest or parts of it. Here an example: ~~~ >>> from werkzeug.test import create_environ >>> env = create_environ("/?param=foo", "http://localhost/script") >>> get_current_url(env) 'http://localhost/script/?param=foo' >>> get_current_url(env, root_only=True) 'http://localhost/script/' >>> get_current_url(env, host_only=True) 'http://localhost/' >>> get_current_url(env, strip_querystring=True) 'http://localhost/script/' ~~~ This optionally it verifies that the host is in a list of trusted hosts.If the host is not in there it will raise a[SecurityError](# "werkzeug.exceptions.SecurityError"). <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>environ</strong> – the WSGI environment to get the current URL from.</li><li><strong>root_only</strong> – set <cite>True</cite> if you only want the root URL.</li><li><strong>strip_querystring</strong> – set to <cite>True</cite> if you don't want the querystring.</li><li><strong>host_only</strong> – set to <cite>True</cite> if the host URL should be returned.</li><li><strong>trusted_hosts</strong> – a list of trusted hosts, see <a class="reference internal" href="#werkzeug.wsgi.host_is_trusted" title="werkzeug.wsgi.host_is_trusted"><tt class="xref py py-func docutils literal"><span class="pre">host_is_trusted()</span></tt></a>for more information.</li></ul></td></tr></tbody></table> werkzeug.wsgi.get_query_string(*environ*) Returns the QUERY_STRING from the WSGI environment. This also takescare about the WSGI decoding dance on Python 3 environments as anative string. The string returned will be restricted to ASCIIcharacters. 0.9 新版功能. | 参数: | **environ** – the WSGI environment object to get the query string from. | |-----|-----| werkzeug.wsgi.get_script_name(*environ*, *charset='utf-8'*, *errors='replace'*) Returns the SCRIPT_NAME from the WSGI environment and properlydecodes it. This also takes care about the WSGI decoding danceon Python 3 environments. if the charset is set to None abytestring is returned. 0.9 新版功能. <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>environ</strong> – the WSGI environment object to get the path from.</li><li><strong>charset</strong> – the charset for the path, or <cite>None</cite> if nodecoding should be performed.</li><li><strong>errors</strong> – the decoding error handling.</li></ul></td></tr></tbody></table> werkzeug.wsgi.get_path_info(*environ*, *charset='utf-8'*, *errors='replace'*) Returns the PATH_INFO from the WSGI environment and properlydecodes it. This also takes care about the WSGI decoding danceon Python 3 environments. if the charset is set to None abytestring is returned. 0.9 新版功能. <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>environ</strong> – the WSGI environment object to get the path from.</li><li><strong>charset</strong> – the charset for the path info, or <cite>None</cite> if nodecoding should be performed.</li><li><strong>errors</strong> – the decoding error handling.</li></ul></td></tr></tbody></table> werkzeug.wsgi.pop_path_info(*environ*, *charset='utf-8'*, *errors='replace'*) Removes and returns the next segment of PATH_INFO, pushing it ontoSCRIPT_NAME. Returns None if there is nothing left on PATH_INFO. If the charset is set to None a bytestring is returned. If there are empty segments ('/foo//bar) these are ignored butproperly pushed to the SCRIPT_NAME: ~~~ >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' ~~~ 0.5 新版功能. 在 0.9 版更改: The path is now decoded and a charset and encodingparameter can be provided. | 参数: | **environ** – the WSGI environment that is modified. | |-----|-----| werkzeug.wsgi.peek_path_info(*environ*, *charset='utf-8'*, *errors='replace'*) Returns the next segment on the PATH_INFO or None if thereis none. Works like [pop_path_info()](# "werkzeug.wsgi.pop_path_info") without modifying theenvironment: ~~~ >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> peek_path_info(env) 'a' >>> peek_path_info(env) 'a' ~~~ If the charset is set to None a bytestring is returned. 0.5 新版功能. 在 0.9 版更改: The path is now decoded and a charset and encodingparameter can be provided. | 参数: | **environ** – the WSGI environment that is checked. | |-----|-----| werkzeug.wsgi.extract_path_info(*environ_or_baseurl*, *path_or_url*, *charset='utf-8'*, *errors='replace'*, *collapse_http_schemes=True*) Extracts the path info from the given URL (or WSGI environment) andpath. The path info returned is a unicode string, not a bytestringsuitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, None is returned. Some examples: ~~~ >>> extract_path_info('http://example.com/app', '/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') u'/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True ~~~ Instead of providing a base URL you can also pass a WSGI environment. 0.6 新版功能. <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>environ_or_baseurl</strong> – a WSGI environment dict, a base URL orbase IRI. This is the root of theapplication.</li><li><strong>path_or_url</strong> – an absolute path from the server root, arelative path (in which case it's the path info)or a full URL. Also accepts IRIs and unicodeparameters.</li><li><strong>charset</strong> – the charset for byte data in URLs</li><li><strong>errors</strong> – the error handling on decode</li><li><strong>collapse_http_schemes</strong> – if set to <cite>False</cite> the algorithm doesnot assume that http and https on thesame server point to the sameresource.</li></ul></td></tr></tbody></table> werkzeug.wsgi.host_is_trusted(*hostname*, *trusted_list*) Checks if a host is trusted against a list. This also takes careof port normalization. 0.9 新版功能. <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>hostname</strong> – the hostname to check</li><li><strong>trusted_list</strong> – a list of hostnames to check against. If ahostname starts with a dot it will match againstall subdomains as well.</li></ul></td></tr></tbody></table> ### Convenience Helpers werkzeug.wsgi.responder(*f*) Marks a function as responder. Decorate a function with it and itwill automatically call the return value as WSGI application. Example: ~~~ @responder def application(environ, start_response): return Response('Hello World!') ~~~ werkzeug.testapp.test_app(*environ*, *start_response*) Simple test application that dumps the environment. You can useit to check if Werkzeug is working properly: ~~~ >>> from werkzeug.serving import run_simple >>> from werkzeug.testapp import test_app >>> run_simple('localhost', 3000, test_app) * Running on http://localhost:3000/ ~~~ The application displays important information from the WSGI environment,the Python interpreter and the installed libraries.
';