wsgiref
— WSGI Utilities and Reference ImplementationWSGI实用程序和参考实现¶
The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Web服务器网关接口(WSGI)是用Python编写的Web服务器软件和Web应用程序之间的标准接口。Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers.有了一个标准的界面,就可以很容易地使用一个支持WSGI和许多不同web服务器的应用程序。
Only authors of web servers and programming frameworks need to know every detail and corner case of the WSGI design. 只有web服务器和编程框架的作者需要知道WSGI设计的每个细节和细节。You don’t need to understand every detail of WSGI just to install a WSGI application or to write a web application using an existing framework.仅仅为了安装WSGI应用程序或使用现有框架编写web应用程序,您不需要了解WSGI的每个细节。
wsgiref
is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. 是WSGI规范的参考实现,可用于将WSGI支持添加到web服务器或框架。It provides utilities for manipulating WSGI environment variables and response headers, base classes for implementing WSGI servers, a demo HTTP server that serves WSGI applications, and a validation tool that checks WSGI servers and applications for conformance to the WSGI specification (PEP 3333).它提供了用于操作WSGI环境变量和响应头的实用程序、用于实现WSGI服务器的基类、为WSGI应用程序提供服务的演示HTTP服务器,以及用于检查WSGI服务器和应用程序是否符合WSGI规范(PEP 3333)的验证工具。
See wsgi.readthedocs.io for more information about WSGI, and links to tutorials and other resources.有关WSGI的更多信息,以及教程和其他资源的链接,请参阅wsgi.readthedocs.io。
wsgiref.util
– WSGI environment utilitiesWSGI环境实用程序¶
This module provides a variety of utility functions for working with WSGI environments. 该模块提供了各种用于处理WSGI环境的实用功能。A WSGI environment is a dictionary containing HTTP request variables as described in PEP 3333. WSGI环境是一个包含HTTP请求变量的字典,如PEP 3333中所述。All of the functions taking an environ parameter expect a WSGI-compliant dictionary to be supplied; please see PEP 3333 for a detailed specification.所有采用environ参数的函数都需要提供符合WSGI的字典;有关详细规范,请参阅PEP 3333。
-
wsgiref.util.
guess_scheme
(environ)¶ Return a guess for whether通过在environ字典中检查wsgi.url_scheme
should be “http” or “https”, by checking for aHTTPS
environment variable in the environ dictionary.HTTPS
环境变量,返回wsgi.url_scheme
应为“http”还是“https”的猜测。The return value is a string.返回值是一个字符串。This function is useful when creating a gateway that wraps CGI or a CGI-like protocol such as FastCGI.当创建封装CGI或类似CGI的协议(如FastCGI)的网关时,此函数很有用。Typically, servers providing such protocols will include a通常,当通过SSL接收请求时,提供此类协议的服务器将包括一个值为“1”、“yes”或“on”的HTTPS
variable with a value of “1”, “yes”, or “on” when a request is received via SSL.HTTPS
变量。So, this function returns “https” if such a value is found, and “http” otherwise.因此,如果找到这样的值,则该函数返回“https”,否则返回“http”。
-
wsgiref.util.
request_uri
(environ, include_query=True)¶ Return the full request URI, optionally including the query string, using the algorithm found in the “URL Reconstruction” section of PEP 3333.使用PEP 3333“URL重建”部分中的算法返回完整的请求URI,可以选择包括查询字符串。If include_query is false, the query string is not included in the resulting URI.如果include_query为false
,则查询字符串不包括在结果URI中。
-
wsgiref.util.
application_uri
(environ)¶ Similar to与request_uri()
, except that thePATH_INFO
andQUERY_STRING
variables are ignored.request_uri()
类似,只是忽略了PATH_INFO
和QUERY_STRING
变量。The result is the base URI of the application object addressed by the request.结果是由请求寻址的应用程序对象的基本URI。
-
wsgiref.util.
shift_path_info
(environ)¶ Shift a single name from将单个名称从PATH_INFO
toSCRIPT_NAME
and return the name.PATH_INFO
移到SCRIPT_NAME
并返回名称。The environ dictionary is modified in-place; use a copy if you need to keep the originalenviron字典会被原地修改;如果需要保持原始PATH_INFO
orSCRIPT_NAME
intact.PATH_INFO
或SCRIPT_NAME
不变,请使用副本。If there are no remaining path segments in如果PATH_INFO
,None
is returned.PATH_INFO
中没有剩余的路径段,则会返回None
。Typically, this routine is used to process each portion of a request URI path, for example to treat the path as a series of dictionary keys.通常,此例程用于处理请求URI路径的每个部分,例如将路径视为一系列字典键。This routine modifies the passed-in environment to make it suitable for invoking another WSGI application that is located at the target URI.该例程修改传入的环境,使其适合调用位于目标URI的另一个WSGI应用程序。For example, if there is a WSGI application at例如,如果在/foo
, and the request URI path is/foo/bar/baz
, and the WSGI application at/foo
callsshift_path_info()
, it will receive the string “bar”, and the environment will be updated to be suitable for passing to a WSGI application at/foo/bar
./foo
处有一个WSGI应用程序,并且请求URI路径为/foo/bar/baz
,/foo
处的WSGI应用程序调用shift_path_info()
,它将接收字符串“bar”,并且环境将被更新以适合传递给在/foo/bar
处的WSGI应用程序。That is,也就是说,SCRIPT_NAME
will change from/foo
to/foo/bar
, andPATH_INFO
will change from/bar/baz
to/baz
.SCRIPT_NAME
将从/foo
更改为/foo/bar
,PATH_INFO
将从/bar/baz
更改为/baz
。When当PATH_INFO
is just a “/”, this routine returns an empty string and appends a trailing slash toSCRIPT_NAME
, even though empty path segments are normally ignored, andSCRIPT_NAME
doesn’t normally end in a slash.PATH_INFO
只是一个“/”时,该例程返回一个空字符串,并在SCRIPT_NAME
后面附加一个斜杠,即使空路径段通常被忽略,并且SCRIPT_NAME
通常不以斜杠结尾。This is intentional behavior, to ensure that an application can tell the difference between URIs ending in这是故意的行为,以确保应用程序在使用此例程进行对象遍历时可以区分以/x
from ones ending in/x/
when using this routine to do object traversal./x
结尾的URI和以/x/
结尾的URI之间的差异。
-
wsgiref.util.
setup_testing_defaults
(environ)¶ Update environ with trivial defaults for testing purposes.出于测试目的,使用微不足道的默认值更新environ。This routine adds various parameters required for WSGI, including该例程添加了WSGI所需的各种参数,包括HTTP_HOST
,SERVER_NAME
,SERVER_PORT
,REQUEST_METHOD
,SCRIPT_NAME
,PATH_INFO
, and all of the PEP 3333-definedwsgi.*
variables.HTTP_HOST
、SERVER_NAME
、SERVER_PORT
、REQUEST_METHOD
、SCRIPT_NAME
、PATH_INFO
以及所有PEP 3333定义的wsgi.*
变量。It only supplies default values, and does not replace any existing settings for these variables.它只提供默认值,不替换这些变量的任何现有设置。This routine is intended to make it easier for unit tests of WSGI servers and applications to set up dummy environments.该例程旨在使WSGI服务器和应用程序的单元测试更容易建立虚拟环境。It should NOT be used by actual WSGI servers or applications, since the data is fake!它不应该被实际的WSGI服务器或应用程序使用,因为数据是假的!Example usage:
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server
# A relatively simple WSGI application. It's going to print out the
# environment dictionary after being updated by setup_testing_defaults
def simple_app(environ, start_response):
setup_testing_defaults(environ)
status = '200 OK'
headers = [('Content-type', 'text/plain; charset=utf-8')]
start_response(status, headers)
ret = [("%s: %s\n" % (key, value)).encode("utf-8")
for key, value in environ.items()]
return ret
with make_server('', 8000, simple_app) as httpd:
print("Serving on port 8000...")
httpd.serve_forever()
In addition to the environment functions above, the 除了上述环境功能外,wsgiref.util
module also provides these miscellaneous utilities:wsgiref.util
模块还提供了以下各种实用程序:
-
wsgiref.util.
is_hop_by_hop
(header_name)¶ Return如果“header_name”是RFC 2616定义的HTTP/1.1“逐跳”头,则返回True
if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by RFC 2616.True
。
-
class
wsgiref.util.
FileWrapper
(filelike, blksize=8192)¶ A wrapper to convert a file-like object to an iterator.将类似文件的对象转换为迭代器的包装器。The resulting objects support both为了与Python 2.1和Jython兼容,生成的对象同时支持__getitem__()
and__iter__()
iteration styles, for compatibility with Python 2.1 and Jython.__getitem__()
和__iter__()
迭代样式。As the object is iterated over, the optional blksize parameter will be repeatedly passed to the filelike object’s当对象被迭代时,可选的blksize参数将被反复传递给filelike对象的read()
method to obtain bytestrings to yield.read()
方法,以获得bytestring。When当read()
returns an empty bytestring, iteration is ended and is not resumable.read()
返回一个空的bytestring时,迭代结束并且不可恢复。If filelike has a如果filelike有一个close()
method, the returned object will also have aclose()
method, and it will invoke the filelike object’sclose()
method when called.close()
方法,则返回的对象也将有一个close()
方法,并且在调用时将调用filelike对象的close()
方法。Example usage:示例用法:from io import StringIO
from wsgiref.util import FileWrapper
# We're using a StringIO-buffer for as the file-like object
filelike = StringIO("This is an example file-like object"*10)
wrapper = FileWrapper(filelike, blksize=5)
for chunk in wrapper:
print(chunk)Deprecated since version 3.8:自版本3.8以来已弃用:Support for不推荐支持sequence protocol
is deprecated.sequence protocol
。
wsgiref.headers
– WSGI response header toolsWSGI响应头工具¶
This module provides a single class, 该模块提供了一个类Headers
, for convenient manipulation of WSGI response headers using a mapping-like interface.Headers
,用于使用类似映射的接口方便地操作WSGI响应头。
-
class
wsgiref.headers.
Headers
([headers])¶ Create a mapping-like object wrapping headers, which must be a list of header name/value tuples as described in PEP 3333.创建类似对象包装headers的映射,该映射必须是PEP 3333中描述的头名称/值元组列表。The default value of headers is an empty list.headers的默认值为空列表。Headers
objects support typical mapping operations including对象支持典型的映射操作,包括__getitem__()
,get()
,__setitem__()
,setdefault()
,__delitem__()
and__contains__()
.__getitem__()
、get()
、__setitem__()
、setdefault()
、__delitem__()
和__contains__()
。For each of these methods, the key is the header name (treated case-insensitively), and the value is the first value associated with that header name.对于这些方法中的每一种,关键是标头名称(不区分大小写),该值是与该标头名称相关联的第一个值。Setting a header deletes any existing values for that header, then adds a new value at the end of the wrapped header list.设置标头会删除该标头的任何现有值,然后在已包装标头列表的末尾添加一个新值。Headers’ existing order is generally maintained, with new headers added to the end of the wrapped list.标题的现有顺序通常保持不变,新标题添加到包装列表的末尾。Unlike a dictionary,与字典不同,当您尝试获取或删除不在已包装标头列表中的键时,Headers
objects do not raise an error when you try to get or delete a key that isn’t in the wrapped header list.Headers
对象不会引发错误。Getting a nonexistent header just returns获取一个不存在的头只会返回None
, and deleting a nonexistent header does nothing.None
,而删除一个不存在的头则没有任何作用。Headers
objects also support对象还支持keys()
,values()
, anditems()
methods.keys()
、values()
和items()
方法。The lists returned by如果存在多值标题,则由keys()
anditems()
can include the same key more than once if there is a multi-valued header.keys()
和items()
返回的列表可以多次包含同一个键。Thelen()
of aHeaders
object is the same as the length of itsitems()
, which is the same as the length of the wrapped header list.Headers
对象的len()
与其items()
的长度相同,后者与包装的标题列表的长度相同。In fact, the事实上,items()
method just returns a copy of the wrapped header list.items()
方法只返回包装的标题列表的副本。Calling对bytes()
on aHeaders
object returns a formatted bytestring suitable for transmission as HTTP response headers.Headers
对象调用bytes()
将返回适合作为HTTP响应头传输的格式化bytestring。Each header is placed on a line with its value, separated by a colon and a space.每个标题都放置在一行上,带有其值,由冒号和空格分隔。Each line is terminated by a carriage return and line feed, and the bytestring is terminated with a blank line.每一行都由回车和换行终止,bytestring用一个空行终止。In addition to their mapping interface and formatting features,除了映射接口和格式功能外,Headers
objects also have the following methods for querying and adding multi-valued headers, and for adding headers with MIME parameters:Headers
对象还具有以下方法,用于查询和添加多值头,以及添加带有MIME参数的头:-
get_all
(name)¶ Return a list of all the values for the named header.返回命名标头的所有值的列表。The returned list will be sorted in the order they appeared in the original header list or were added to this instance, and may contain duplicates.返回的列表将按照它们在原始标题列表中出现或添加到此实例中的顺序进行排序,并且可能包含重复项。Any fields deleted and re-inserted are always appended to the header list.删除和重新插入的任何字段始终附加到标题列表中。If no fields exist with the given name, returns an empty list.如果不存在具有给定名称的字段,则返回空列表。
-
add_header
(name, value, **_params)¶ Add a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments.添加一个(可能是多值)标头,其中包含通过关键字参数指定的可选MIME参数。name
is the header field to add.是要添加的标题字段。Keyword arguments can be used to set MIME parameters for the header field.关键字参数可用于设置标头字段的MIME参数。Each parameter must be a string or每个参数必须是字符串或None
.None
。Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes.参数名中的下划线转换为破折号,因为破折号在Python标识符中是非法的,但许多MIME参数名包含破折号。If the parameter value is a string, it is added to the header value parameters in the form如果参数值是字符串,则以name="value"
.name="value"
的形式将其添加到标题值参数中。If it is如果为None
, only the parameter name is added.None
,则只添加参数名称。(This is used for MIME parameters without a value.)(这用于没有值的MIME参数。)Example usage:示例用法:h.add_header('content-disposition', 'attachment', filename='bud.gif')
The above will add a header that looks like this:上面将添加如下标题:Content-Disposition: attachment; filename="bud.gif"
Changed in version 3.5:版本3.5中更改: headersparameter is optional.参数是可选的。-
wsgiref.simple_server
– a simple WSGI HTTP server一个简单的WSGI HTTP服务器¶
This module implements a simple HTTP server (based on 该模块实现了一个简单的HTTP服务器(基于http.server
) that serves WSGI applications. http.server
),为WSGI应用程序提供服务。Each server instance serves a single WSGI application on a given host and port. 每个服务器实例为给定主机和端口上的单个WSGI应用程序提供服务。If you want to serve multiple applications on a single host and port, you should create a WSGI application that parses 如果您想在单个主机和端口上为多个应用程序提供服务,那么应该创建一个WSGI应用程序,该应用程序解析PATH_INFO
to select which application to invoke for each request. PATH_INFO
,以选择为每个请求调用哪个应用程序。(E.g., using the (例如,使用shift_path_info()
function from wsgiref.util
.)wsgiref.util
中的shift_path_info()
函数。)
-
wsgiref.simple_server.
make_server
(host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler)¶ Create a new WSGI server listening on host and port, accepting connections for app.创建一个新的WSGI服务器,侦听host和port,接受应用程序的连接。The return value is an instance of the supplied server_class, and will process requests using the specified handler_class.返回值是提供的server_class的实例,将使用指定的handler_class处理请求。app must be a WSGI application object, as defined by PEP 3333.app必须是WSGI应用程序对象,如PEP 3333所定义。Example usage:示例用法:from wsgiref.simple_server import make_server, demo_app
with make_server('', 8000, demo_app) as httpd:
print("Serving HTTP on port 8000...")
# Respond to requests until process is killed
httpd.serve_forever()
# Alternative: serve one request, then exit
httpd.handle_request()
-
wsgiref.simple_server.
demo_app
(environ, start_response)¶ This function is a small but complete WSGI application that returns a text page containing the message “Hello world!” and a list of the key/value pairs provided in the environ parameter.此函数是一个小型但完整的WSGI应用程序,它返回一个包含消息“Hello world!”以及environ参数中提供的键/值对列表。It’s useful for verifying that a WSGI server (such as这对于验证WSGI服务器(例如wsgiref.simple_server
) is able to run a simple WSGI application correctly.wsgiref.simple_server
)是否能够正确运行简单的WSGI应用程序非常有用。
-
class
wsgiref.simple_server.
WSGIServer
(server_address, RequestHandlerClass)¶ Create a创建WSGIServer
instance.WSGIServer
实例。server_address should be aserver_address应该是一个(host,port)
tuple, and RequestHandlerClass should be the subclass ofhttp.server.BaseHTTPRequestHandler
that will be used to process requests.(host,port)
元组,RequestHandlerClass应该是用于处理请求的http.server.BaseHTTPRequestHandler
的子类。You do not normally need to call this constructor, as the通常不需要调用此构造函数,因为make_server()
function can handle all the details for you.make_server()
函数可以为您处理所有细节。WSGIServer
is a subclass of是http.server.HTTPServer
, so all of its methods (such asserve_forever()
andhandle_request()
) are available.http.server.HTTPServer
的子类,因此其所有方法(例如serve_forever()
和handle_request()
)都可用。WSGIServer
also provides these WSGI-specific methods:还提供了这些特定于WSGI的方法:-
set_app
(application)¶ Sets the callable application as the WSGI application that will receive requests.将可调用application设置为将接收请求的WSGI应用程序。
-
get_app
()¶ Returns the currently-set application callable.返回当前设置的可调用应用程序。
Normally, however, you do not need to use these additional methods, as然而,通常情况下,您不需要使用这些额外的方法,因为set_app()
is normally called bymake_server()
, and theget_app()
exists mainly for the benefit of request handler instances.set_app()
通常由make_server()
调用,而get_app()
的存在主要是为了请求处理程序实例。-
-
class
wsgiref.simple_server.
WSGIRequestHandler
(request, client_address, server)¶ Create an HTTP handler for the given request (i.e. a socket), client_address (a为给定的request(即套接字)、client_address((host,port)
tuple), and server (WSGIServer
instance).(host,port)
元组)和server(WSGIServer
实例)创建HTTP处理程序。You do not need to create instances of this class directly; they are automatically created as needed by您不需要直接创建此类的实例;它们由WSGIServer
objects.WSGIServer
对象根据需要自动创建。You can, however, subclass this class and supply it as a handler_class to the但是,您可以对该类进行子类化,并将其作为handler_class提供给make_server()
function.make_server()
函数。Some possibly relevant methods for overriding in subclasses:在子类中重写的一些可能相关方法:-
get_environ
()¶ Returns a dictionary containing the WSGI environment for a request.返回包含请求的WSGI环境的字典。The default implementation copies the contents of the默认实现复制WSGIServer
object’sbase_environ
dictionary attribute and then adds various headers derived from the HTTP request.WSGIServer
对象的base_environ
目录属性的内容,然后添加从HTTP请求派生的各种头。Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in PEP 3333.对该方法的每次调用都应返回一个新字典,其中包含PEP 3333中指定的所有相关CGI环境变量。
-
get_stderr
()¶ Return the object that should be used as the返回应该用作wsgi.errors
stream.wsgi.errors
流的对象。The default implementation just returns默认实现只返回sys.stderr
.sys.stderr
。
-
handle
()¶ Process the HTTP request.处理HTTP请求。The default implementation creates a handler instance using a默认实现使用wsgiref.handlers
class to implement the actual WSGI application interface.wsgiref.handlers
类创建处理程序实例,以实现实际的WSGI应用程序接口。
-
wsgiref.validate
— WSGI conformance checkerWSGI一致性检查器¶
When creating new WSGI application objects, frameworks, servers, or middleware, it can be useful to validate the new code’s conformance using 在创建新的WSGI应用程序对象、框架、服务器或中间件时,使用wsgiref.validate
. wsgiref.validate
验证新代码的一致性可能会很有用。This module provides a function that creates WSGI application objects that validate communications between a WSGI server or gateway and a WSGI application object, to check both sides for protocol conformance.该模块提供了一个创建WSGI应用程序对象的功能,该对象验证WSGI服务器或网关与WSGI应用程序对象之间的通信,以检查双方的协议一致性。
Note that this utility does not guarantee complete PEP 3333 compliance; an absence of errors from this module does not necessarily mean that errors do not exist. 注意,该实用程序不保证完全符合PEP 3333;该模块没有错误并不一定意味着不存在错误。However, if this module does produce an error, then it is virtually certain that either the server or application is not 100% compliant.但是,如果此模块确实产生错误,那么实际上可以肯定的是,服务器或应用程序不是100%兼容的。
This module is based on the 该模块基于Ian Bicking的“Python粘贴”库中的paste.lint
module from Ian Bicking’s “Python Paste” library.paste.lint
模块。
-
wsgiref.validate.
validator
(application)¶ Wrap application and return a new WSGI application object.包装application并返回新的WSGI应用程序对象。The returned application will forward all requests to the original application, and will check that both the application and the server invoking it are conforming to the WSGI specification and to RFC 2616.返回的应用程序将所有请求转发给原始application,并检查application和调用它的服务器是否符合WSGI规范和RFC 2616。Any detected nonconformance results in an任何检测到的不符合项都会导致提出AssertionError
being raised; note, however, that how these errors are handled is server-dependent.AssertionError
;然而,请注意,这些错误的处理方式取决于服务器。For example,例如,wsgiref.simple_server
and other servers based onwsgiref.handlers
(that don’t override the error handling methods to do something else) will simply output a message that an error has occurred, and dump the traceback tosys.stderr
or some other error stream.wsgiref.simple_server
和基于wsgiref.handlers
的其他服务器(不会覆盖错误处理方法以执行其他操作)将只输出一条发生错误的消息,并将回溯转储到sys.stderr
或其他一些错误流。This wrapper may also generate output using the该包装器还可以使用warnings
module to indicate behaviors that are questionable but which may not actually be prohibited by PEP 3333.warnings
模块生成输出,以指示可疑但实际上可能未被PEP 3333禁止的行为。Unless they are suppressed using Python command-line options or the除非使用Python命令行选项或warnings
API, any such warnings will be written tosys.stderr
(notwsgi.errors
, unless they happen to be the same object).warnings
API抑制这些警告,否则任何此类警告都将写入sys.stderr
(而不是wsgi.errors
,除非它们恰好是同一个对象)。Example usage:示例用法:from wsgiref.validate import validator
from wsgiref.simple_server import make_server
# Our callable object which is intentionally not compliant to the
# standard, so the validator is going to break
def simple_app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain')] # HTTP Headers
start_response(status, headers)
# This is going to break because we need to return a list, and
# the validator is going to inform us
return b"Hello World"
# This is the application wrapped in a validator
validator_app = validator(simple_app)
with make_server('', 8000, validator_app) as httpd:
print("Listening on port 8000....")
httpd.serve_forever()
wsgiref.handlers
– server/gateway base classes服务器/网关基类¶
This module provides base handler classes for implementing WSGI servers and gateways. 该模块提供了用于实现WSGI服务器和网关的基本处理程序类。These base classes handle most of the work of communicating with a WSGI application, as long as they are given a CGI-like environment, along with input, output, and error streams.这些基类处理与WSGI应用程序通信的大部分工作,只要它们具有类似CGI的环境,以及输入、输出和错误流。
-
class
wsgiref.handlers.
CGIHandler
¶ CGI-based invocation via通过sys.stdin
,sys.stdout
,sys.stderr
andos.environ
.sys.stdin
、sys.stdout
、sys.stderr
和os.environ
进行基于CGI的调用。This is useful when you have a WSGI application and want to run it as a CGI script.当您有WSGI应用程序并希望将其作为CGI脚本运行时,这非常有用。Simply invoke只需调用CGIHandler().run(app)
, whereapp
is the WSGI application object you wish to invoke.CGIHandler().run(app)
,其中app
是您希望调用的WSGI应用程序对象。This class is a subclass of该类是BaseCGIHandler
that setswsgi.run_once
to true,wsgi.multithread
to false, andwsgi.multiprocess
to true, and always usessys
andos
to obtain the necessary CGI streams and environment.BaseCGIHandler
的子类,它将wsgi.run_once
设置为true
,wsgi.multithread
设置为false
,wsgi.multiprocess
设置为true
,并始终使用sys
和os
获取必要的CGI流和环境。
-
class
wsgiref.handlers.
IISCGIHandler
¶ A specialized alternative toCGIHandler
, for use when deploying on Microsoft’s IIS web server, without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7).CGIHandler
的专用替代品,用于在Microsoft的IIS web服务器上部署时,无需设置配置allowPathInfo
选项(IIS>=7)或元数据库allowPathInfoForScriptMappings
选项(IIS<7)。By default, IIS gives a默认情况下,IIS提供的PATH_INFO
that duplicates theSCRIPT_NAME
at the front, causing problems for WSGI applications that wish to implement routing.PATH_INFO
与前面的SCRIPT_NAME
重复,这会给希望实现路由的WSGI应用程序带来问题。This handler strips any such duplicated path.此处理程序将删除任何此类重复路径。IIS can be configured to pass the correctIIS可以配置为传递正确的PATH_INFO
, but this causes another bug wherePATH_TRANSLATED
is wrong.PATH_INFO
,但这会导致另一个错误,其中PATH_TRANSLATED
是错误。Luckily this variable is rarely used and is not guaranteed by WSGI.幸运的是,这个变量很少使用,WSGI也不保证。On IIS<7, though, the setting can only be made on a vhost level, affecting all other script mappings, many of which break when exposed to the但是,在IIS<7时,只能在vhost级别上进行设置,这会影响所有其他脚本映射,其中许多映射在暴露于PATH_TRANSLATED
bug.PATH_TRANSLATED
的错误时会中断。For this reason IIS<7 is almost never deployed with the fix (Even IIS7 rarely uses it because there is still no UI for it.).由于这个原因,IIS<7几乎从未与该补丁一起部署(即使IIS7也很少使用它,因为它仍然没有UI)。There is no way for CGI code to tell whether the option was set, so a separate handler class is provided.CGI代码无法判断是否设置了选项,因此提供了一个单独的处理程序类。It is used in the same way as它的使用方式与CGIHandler
, i.e., by callingIISCGIHandler().run(app)
, whereapp
is the WSGI application object you wish to invoke.CGIHandler
相同,即调用IISCGIHandler().run(app)
,其中app
是您希望调用的WSGI应用程序对象。New in version 3.2.版本3.2中新增。
-
class
wsgiref.handlers.
BaseCGIHandler
(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)¶ Similar to与CGIHandler
, but instead of using thesys
andos
modules, the CGI environment and I/O streams are specified explicitly.CGIHandler
类似,但不是使用sys
和os
模块,而是显式指定CGI环境和I/O流。The multithread and multiprocess values are used to set themultithread和multiprocess值用于为处理程序实例运行的任何应用程序设置wsgi.multithread
andwsgi.multiprocess
flags for any applications run by the handler instance.wsgi.multithread
和wsgi.multiprocess
标志。This class is a subclass of此类是SimpleHandler
intended for use with software other than HTTP “origin servers”.SimpleHandler
的子类,用于HTTP“源服务器”以外的软件。If you are writing a gateway protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a如果您正在编写一个网关协议实现(例如CGI、FastCGI、SCGI等),它使用Status:
header to send an HTTP status, you probably want to subclass this instead ofSimpleHandler
.Status:
标头来发送HTTP状态,那么您可能希望将其子类化,而不是用SimpleHandler
。
-
class
wsgiref.handlers.
SimpleHandler
(stdin, stdout, stderr, environ, multithread=True, multiprocess=False)¶ Similar to类似于BaseCGIHandler
, but designed for use with HTTP origin servers.BaseCGIHandler
,但设计用于HTTP源服务器。If you are writing an HTTP server implementation, you will probably want to subclass this instead of如果您正在编写HTTP服务器实现,您可能希望将其子类化,而不是BaseCGIHandler
.BaseCGIHandler
。This class is a subclass of此类是BaseHandler
.BaseHandler
的子类。It overrides the它重写了__init__()
,get_stdin()
,get_stderr()
,add_cgi_vars()
,_write()
, and_flush()
methods to support explicitly setting the environment and streams via the constructor.__init__()
、get_stdin()
、get_stderr()
、add_cgi_vars()
、_write()
和_flush()
方法,以支持通过构造函数显式设置环境和流。The supplied environment and streams are stored in the提供的环境和流存储在stdin
,stdout
,stderr
, andenviron
attributes.stdin
、stdout
、stderr
和environ
属性中。Thestdout的write()
method of stdout should write each chunk in full, likeio.BufferedIOBase
.write()
方法应该完整地写入每个块,就像io.BufferedIOBase
一样。
-
class
wsgiref.handlers.
BaseHandler
¶ This is an abstract base class for running WSGI applications.这是用于运行WSGI应用程序的抽象基类。Each instance will handle a single HTTP request, although in principle you could create a subclass that was reusable for multiple requests.每个实例将处理一个HTTP请求,尽管原则上您可以创建一个可用于多个请求的子类。BaseHandler
instances have only one method intended for external use:实例只有一种用于外部使用的方法:-
run
(app)¶ Run the specified WSGI application, app.运行指定的WSGI应用程序app。
All of the other所有其他BaseHandler
methods are invoked by this method in the process of running the application, and thus exist primarily to allow customizing the process.BaseHandler
方法都是在运行应用程序的过程中由该方法调用的,因此其存在主要是为了允许自定义过程。The following methods MUST be overridden in a subclass:必须在子类中重写以下方法:-
_write
(data)¶ Buffer the bytes data for transmission to the client.缓冲字节data以传输到客户端。It’s okay if this method actually transmits the data;如果这种方法真的传输了数据,那也没关系;当底层系统实际上有这样的区别时,BaseHandler
just separates write and flush operations for greater efficiency when the underlying system actually has such a distinction.BaseHandler
只是将写操作和刷新操作分离开来以提高效率。
-
_flush
()¶ Force buffered data to be transmitted to the client.强制将缓冲数据传输到客户端。It’s okay if this method is a no-op (i.e., if如果这个方法是no-op(即,如果_write()
actually sends the data)._write()
实际发送数据),则可以。
-
get_stdin
()¶ Return an input stream object suitable for use as the返回适合用作当前正在处理的请求的wsgi.input
of the request currently being processed.wsgi.input
的输入流对象。
-
get_stderr
()¶ Return an output stream object suitable for use as the返回适合用作当前正在处理的请求的wsgi.errors
of the request currently being processed.wsgi.error
的输出流对象。
-
add_cgi_vars
()¶ Insert CGI variables for the current request into the将当前请求的CGI变量插入environ
attribute.environ
属性。
Here are some other methods and attributes you may wish to override.以下是您可能希望覆盖的其他一些方法和属性。This list is only a summary, however, and does not include every method that can be overridden.然而,这个列表只是一个摘要,并不包括所有可以重写的方法。You should consult the docstrings and source code for additional information before attempting to create a customized在尝试创建自定义的BaseHandler
subclass.BaseHandler
子类之前,您应该参考docstring和源代码以获取更多信息。Attributes and methods for customizing the WSGI environment:自定义WSGI环境的属性和方法:-
wsgi_multithread
¶ The value to be used for thewsgi.multithread
environment variable.wsgi.multithread
环境变量要使用的值。It defaults to true in在BaseHandler
, but may have a different default (or be set by the constructor) in the other subclasses.BaseHandler
中默认为true
,但在其他子类中可能有不同的默认值(或由构造函数设置)。
-
wsgi_multiprocess
¶ The value to be used for thewsgi.multiprocess
environment variable.wsgi.multiprocess
环境变量要使用的值。It defaults to true in在BaseHandler
, but may have a different default (or be set by the constructor) in the other subclasses.BaseHandler
中默认为true
,但在其他子类中可能有不同的默认值(或由构造函数设置)。
-
wsgi_run_once
¶ The value to be used for the用于wsgi.run_once
environment variable.wsgi.run_once
环境变量的值。It defaults to false in它在BaseHandler
, butCGIHandler
sets it to true by default.BaseHandler
中默认为false
,但CGIHandler
在默认情况下将其设置为true
。
-
os_environ
¶ The default environment variables to be included in every request’s WSGI environment.要包含在每个请求的WSGI环境中的默认环境变量。By default, this is a copy of默认情况下,这是os.environ
at the time thatwsgiref.handlers
was imported, but subclasses can either create their own at the class or instance level.wsgiref.handlers
导入时os.environ
的副本,但子类可以在类或实例级别创建自己的副本。Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances.请注意,字典应被视为只读,因为默认值在多个类和实例之间共享。
-
server_software
¶ If the如果设置了origin_server
attribute is set, this attribute’s value is used to set the defaultSERVER_SOFTWARE
WSGI environment variable, and also to set a defaultServer:
header in HTTP responses.origin_server
属性,则该属性的值用于设置默认的SERVER_SOFTWARE
WSGI环境变量,并用于在HTTP响应中设置默认的Server:
标头。It is ignored for handlers (such as对于不是HTTP源服务器的处理程序(例如BaseCGIHandler
andCGIHandler
) that are not HTTP origin servers.BaseCGIHandler
和CGIHandler
),它被忽略。Changed in version 3.3:版本3.3中更改:The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc.术语“Python”被替换为特定于实现的术语,如“CPython”、“Jython”等。
-
get_scheme
()¶ Return the URL scheme being used for the current request.返回当前请求使用的URL方案。The default implementation uses the默认实现使用guess_scheme()
function fromwsgiref.util
to guess whether the scheme should be “http” or “https”, based on the current request’senviron
variables.wsgiref.util
中的guess_scheme()
函数根据当前请求的环境变量猜测方案是“http”还是“https”。
-
setup_environ
()¶ Set the将environ
attribute to a fully-populated WSGI environment.environ
属性设置为完全填充的WSGI环境。The default implementation uses all of the above methods and attributes, plus the默认实现使用上述所有方法和属性,以及get_stdin()
,get_stderr()
, andadd_cgi_vars()
methods and thewsgi_file_wrapper
attribute.get_stdin()
、get_stderr()
和add_cgi_vars()
方法和wsgi_file_wrapper
属性。It also inserts a只要SERVER_SOFTWARE
key if not present, as long as theorigin_server
attribute is a true value and theserver_software
attribute is set.origin_server
属性为真值且server_software
属性已设置,则它还会插入一个SERVER_SOFTWARE
键(如果不存在)。
Methods and attributes for customizing exception handling:用于自定义异常处理的方法和属性:-
log_exception
(exc_info)¶ Log the exc_info tuple in the server log.在服务器日志中记录exc_info元组。exc_infois a是(type, value, traceback)
tuple.(type, value, traceback)
元组。The default implementation simply writes the traceback to the request’s默认实现只是将回溯写入请求的wsgi.errors
stream and flushes it.wsgi.errors
流并刷新它。Subclasses can override this method to change the format or retarget the output, mail the traceback to an administrator, or whatever other action may be deemed suitable.子类可以重写此方法以更改格式或重新定位输出,将回溯邮件发送给管理员,或任何其他认为合适的操作。
-
traceback_limit
¶ The maximum number of frames to include in tracebacks output by the default默认log_exception()
method.log_exception()
方法输出的回溯中包含的最大帧数。If如果为None
, all frames are included.None
,则包括所有帧。
-
error_output
(environ, start_response)¶ This method is a WSGI application to generate an error page for the user.该方法是一个WSGI应用程序,用于为用户生成错误页面。It is only invoked if an error occurs before headers are sent to the client.只有在标头发送到客户端之前发生错误时,才会调用它。This method can access the current error information using此方法可以使用sys.exc_info()
, and should pass that information to start_response when calling it (as described in the “Error Handling” section of PEP 3333).sys.exc_info()
访问当前错误信息,并应在调用时将该信息传递给start_response(如PEP 3333的“错误处理”部分所述)。The default implementation just uses the默认实现只使用error_status
,error_headers
, anderror_body
attributes to generate an output page.error_status
、error_headers
和error_body
属性来生成输出页面。Subclasses can override this to produce more dynamic error output.子类可以覆盖此项以生成更动态的错误输出。Note, however, that it’s not recommended from a security perspective to spit out diagnostics to any old user; ideally, you should have to do something special to enable diagnostic output, which is why the default implementation doesn’t include any.然而,请注意,从安全角度来看,不建议向任何老用户吐出诊断信息;理想情况下,您应该做一些特殊的事情来启用诊断输出,这就是为什么默认实现不包括任何诊断输出。
-
error_status
¶ The HTTP status used for error responses.用于错误响应的HTTP状态。This should be a status string as defined in PEP 3333; it defaults to a 500 code and message.这应该是PEP 3333中定义的状态字符串;它默认为500代码和消息。
-
error_headers
¶ The HTTP headers used for error responses.用于错误响应的HTTP标头。This should be a list of WSGI response headers (这应该是WSGI响应头((name, value)
tuples), as described in PEP 3333.(name, value)
元组的列表,如PEP 3333中所述。The default list just sets the content type to默认列表只是将内容类型设置为text/plain
.text/plain
。
-
error_body
¶ The error response body.错误响应主体。This should be an HTTP response body bytestring.这应该是一个HTTP响应体bytestring。It defaults to the plain text, “A server error occurred.默认为纯文本,“发生服务器错误。Please contact the administrator.”请联系管理员。"
Methods and attributes for PEP 3333’s “Optional Platform-Specific File Handling” feature:PEP 3333“可选平台特定文件处理”功能的方法和属性:-
wsgi_file_wrapper
¶ Awsgi.file_wrapper
factory, orNone
.wsgi.file_wrapper
工厂,或None
。The default value of this attribute is the该属性的默认值是wsgiref.util.FileWrapper
class.wsgiref.util.FileWrapper
类。
-
sendfile
()¶ Override to implement platform-specific file transmission.覆盖以实现平台特定的文件传输。This method is called only if the application’s return value is an instance of the class specified by the仅当应用程序的返回值是wsgi_file_wrapper
attribute.wsgi_file_wrapper
属性指定的类的实例时,才会调用此方法。It should return a true value if it was able to successfully transmit the file, so that the default transmission code will not be executed.如果能够成功传输文件,则应返回true
值,以便不会执行默认传输代码。The default implementation of this method just returns a false value.该方法的默认实现只返回一个假值。
Miscellaneous methods and attributes:其他方法和属性:-
origin_server
¶ This attribute should be set to a true value if the handler’s如果处理程序的_write()
and_flush()
are being used to communicate directly to the client, rather than via a CGI-like gateway protocol that wants the HTTP status in a specialStatus:
header._write()
和_flush()
被用于直接与客户端通信,而不是通过类似CGI的网关协议,该协议希望HTTP状态处于特殊Status:
头,则应将该属性设置为true
值。This attribute’s default value is true in该属性的默认值在BaseHandler
, but false inBaseCGIHandler
andCGIHandler
.BaseHandler
中为true
,但在BaseCGIHandler
和CGIHandler
中为false
。
-
http_version
¶ If如果origin_server
is true, this string attribute is used to set the HTTP version of the response set to the client.origin_server
为true
,则此字符串属性用于将响应集的HTTP版本设置为客户端。It defaults to默认为"1.0"
."1.0"
。
-
-
wsgiref.handlers.
read_environ
()¶ Transcode CGI variables from将CGI变量从os.environ
to PEP 3333 “bytes in unicode” strings, returning a new dictionary.os.environ
转换为PEP 3333“bytes in unicode”字符串,返回一个新字典。This function is used by该函数由CGIHandler
andIISCGIHandler
in place of directly usingos.environ
, which is not necessarily WSGI-compliant on all platforms and web servers using Python 3 – specifically, ones where the OS’s actual environment is Unicode (i.e. Windows), or ones where the environment is bytes, but the system encoding used by Python to decode it is anything other than ISO-8859-1 (e.g. Unix systems using UTF-8).CGIHandler
和IISCGIHandler
使用,而不是直接使用os.environ
,os.environ
在使用Python 3的所有平台和web服务器上都不一定符合WSGI,特别是在操作系统的实际环境为Unicode(即Windows)的平台和服务器上,或者在环境为bytes的平台和服务器上,但是Python用于解码的系统编码不是ISO-8859-1(例如,使用UTF-8的Unix系统)。If you are implementing a CGI-based handler of your own, you probably want to use this routine instead of just copying values out of如果您正在实现自己的基于CGI的处理程序,您可能希望使用此例程,而不是直接从os.environ
directly.os.environ
中复制值。New in version 3.2.版本3.2中新增。
Examples示例¶
This is a working “Hello World” WSGI application:这是一个正在运行的“Hello World”WSGI应用程序:
from wsgiref.simple_server import make_server
# Every WSGI application must have an application object - a callable
# object that accepts two arguments. For that purpose, we're going to
# use a function (note that you're not limited to a function, you can
# use a class for example). The first argument passed to the function
# is a dictionary containing CGI-style environment variables and the
# second variable is the callable object.
def hello_world_app(environ, start_response):
status = '200 OK' # HTTP Status
headers = [('Content-type', 'text/plain; charset=utf-8')] # HTTP Headers
start_response(status, headers)
# The returned object is going to be printed
return [b"Hello World"]
with make_server('', 8000, hello_world_app) as httpd:
print("Serving on port 8000...")
# Serve until process is killed
httpd.serve_forever()
Example of a WSGI application serving the current directory, accept optional directory and port number (default: 8000) on the command line:服务于当前目录的WSGI应用程序示例,在命令行上接受可选目录和端口号(默认值:8000):
#!/usr/bin/env python3
'''
Small wsgiref based web server. Takes a path to serve from and an
optional port number (defaults to 8000), then tries to serve files.
Mime types are guessed from the file names, 404 errors are raised
if the file is not found. Used for the make serve target in Doc.
'''
import sys
import os
import mimetypes
from wsgiref import simple_server, util
def app(environ, respond):
fn = os.path.join(path, environ['PATH_INFO'][1:])
if '.' not in fn.split(os.path.sep)[-1]:
fn = os.path.join(fn, 'index.html')
type = mimetypes.guess_type(fn)[0]
if os.path.exists(fn):
respond('200 OK', [('Content-Type', type)])
return util.FileWrapper(open(fn, "rb"))
else:
respond('404 Not Found', [('Content-Type', 'text/plain')])
return [b'not found']
if __name__ == '__main__':
path = sys.argv[1] if len(sys.argv) > 1 else os.getcwd()
port = int(sys.argv[2]) if len(sys.argv) > 2 else 8000
httpd = simple_server.make_server('', port, app)
print("Serving {} on port {}, control-C to stop".format(path, port))
try:
httpd.serve_forever()
except KeyboardInterrupt:
print("Shutting down.")
httpd.server_close()