wsgiref — WSGI Utilities and Reference Implementation¶
Source code:Lib/wsgiref
The Web Server Gateway Interface (WSGI) is a standard interface between webserver software and web applications written in Python. Having a standardinterface makes it easy to use an application that supports WSGI with a numberof different web servers.
Only authors of web servers and programming frameworks need to know every detailand corner case of the WSGI design. You don’t need to understand every detailof WSGI just to install a WSGI application or to write a web application usingan existing framework.
wsgiref is a reference implementation of the WSGI specification that canbe used to add WSGI support to a web server or framework. It provides utilitiesfor manipulating WSGI environment variables and response headers, base classesfor implementing WSGI servers, a demo HTTP server that serves WSGI applications,types for static type checking,and a validation tool that checks WSGI servers and applications for conformanceto the WSGI specification (PEP 3333).
Seewsgi.readthedocs.io for more information about WSGI, and linksto tutorials and other resources.
wsgiref.util – WSGI environment utilities¶
This module provides a variety of utility functions for working with WSGIenvironments. A WSGI environment is a dictionary containing HTTP requestvariables as described inPEP 3333. All of the functions taking anenvironparameter expect a WSGI-compliant dictionary to be supplied; please seePEP 3333 for a detailed specification andWSGIEnvironment for a type alias that can be usedin type annotations.
- wsgiref.util.guess_scheme(environ)¶
Return a guess for whether
wsgi.url_schemeshould be “http” or “https”, bychecking for aHTTPSenvironment variable in theenviron dictionary. Thereturn value is a string.This function is useful when creating a gateway that wraps CGI or a CGI-likeprotocol such as FastCGI. Typically, servers providing such protocols willinclude a
HTTPSvariable with a value of “1”, “yes”, or “on” when a requestis received via SSL. So, this function returns “https” if such a value isfound, and “http” otherwise.
- wsgiref.util.request_uri(environ,include_query=True)¶
Return the full request URI, optionally including the query string, using thealgorithm found in the “URL Reconstruction” section ofPEP 3333. Ifinclude_query is false, the query string is not included in the resulting URI.
- wsgiref.util.application_uri(environ)¶
Similar to
request_uri(), except that thePATH_INFOandQUERY_STRINGvariables are ignored. The result is the base URI of theapplication object addressed by the request.
- wsgiref.util.shift_path_info(environ)¶
Shift a single name from
PATH_INFOtoSCRIPT_NAMEand return the name.Theenviron dictionary ismodified in-place; use a copy if you need to keepthe originalPATH_INFOorSCRIPT_NAMEintact.If there are no remaining path segments in
PATH_INFO,Noneis returned.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. This routinemodifies the passed-in environment to make it suitable for invoking another WSGIapplication that is located at the target URI. For example, if there is a WSGIapplication at
/foo, and the request URI path is/foo/bar/baz, and theWSGI application at/foocallsshift_path_info(), it will receive thestring “bar”, and the environment will be updated to be suitable for passing toa WSGI application at/foo/bar. That is,SCRIPT_NAMEwill change from/footo/foo/bar, andPATH_INFOwill change from/bar/bazto/baz.When
PATH_INFOis just a “/”, this routine returns an empty string andappends a trailing slash toSCRIPT_NAME, even though empty path segments arenormally ignored, andSCRIPT_NAMEdoesn’t normally end in a slash. This isintentional behavior, to ensure that an application can tell the differencebetween URIs ending in/xfrom ones ending in/x/when using thisroutine to do object traversal.
- wsgiref.util.setup_testing_defaults(environ)¶
Updateenviron with trivial defaults for testing purposes.
This routine adds various parameters required for WSGI, including
HTTP_HOST,SERVER_NAME,SERVER_PORT,REQUEST_METHOD,SCRIPT_NAME,PATH_INFO, and all of thePEP 3333-definedwsgi.*variables. Itonly supplies default values, and does not replace any existing settings forthese variables.This routine is intended to make it easier for unit tests of WSGI servers andapplications to set up dummy environments. It should NOT be used by actual WSGIservers or applications, since the data is fake!
Example usage (see also
demo_app()for another example):fromwsgiref.utilimportsetup_testing_defaultsfromwsgiref.simple_serverimportmake_server# A relatively simple WSGI application. It's going to print out the# environment dictionary after being updated by setup_testing_defaultsdefsimple_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")forkey,valueinenviron.items()]returnretwithmake_server('',8000,simple_app)ashttpd:print("Serving on port 8000...")httpd.serve_forever()
In addition to the environment functions above, thewsgiref.util modulealso provides these miscellaneous utilities:
- wsgiref.util.is_hop_by_hop(header_name)¶
Return
Trueif ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined byRFC 2616.
- classwsgiref.util.FileWrapper(filelike,blksize=8192)¶
A concrete implementation of the
wsgiref.types.FileWrapperprotocol used to convert a file-like object to aniterator.The resulting objectsareiterables. As the object is iterated over, theoptionalblksize parameter will be repeatedly passed to thefilelikeobject’sread()method to obtain bytestrings to yield. Whenread()returns an empty bytestring, iteration is ended and is not resumable.Iffilelike has a
close()method, the returned object will also have aclose()method, and it will invoke thefilelike object’sclose()method when called.Example usage:
fromioimportStringIOfromwsgiref.utilimportFileWrapper# We're using a StringIO-buffer for as the file-like objectfilelike=StringIO("This is an example file-like object"*10)wrapper=FileWrapper(filelike,blksize=5)forchunkinwrapper:print(chunk)
Changed in version 3.11:Support for
__getitem__()method has been removed.
wsgiref.headers – WSGI response header tools¶
This module provides a single class,Headers, for convenientmanipulation of WSGI response headers using a mapping-like interface.
- classwsgiref.headers.Headers([headers])¶
Create a mapping-like object wrappingheaders, which must be a list of headername/value tuples as described inPEP 3333. The default value ofheaders isan empty list.
Headersobjects support typical mapping operations including__getitem__(),get(),__setitem__(),setdefault(),__delitem__()and__contains__(). For each ofthese methods, the key is the header name (treated case-insensitively), and thevalue is the first value associated with that header name. Setting a headerdeletes any existing values for that header, then adds a new value at the end ofthe wrapped header list. Headers’ existing order is generally maintained, withnew headers added to the end of the wrapped list.Unlike a dictionary,
Headersobjects do not raise an error when you tryto get or delete a key that isn’t in the wrapped header list. Getting anonexistent header just returnsNone, and deleting a nonexistent header doesnothing.Headersobjects also supportkeys(),values(), anditems()methods. The lists returned bykeys()anditems()caninclude the same key more than once if there is a multi-valued header. Thelen()of aHeadersobject is the same as the length of itsitems(), which is the same as the length of the wrapped header list. Infact, theitems()method just returns a copy of the wrapped header list.Calling
bytes()on aHeadersobject returns a formatted bytestringsuitable for transmission as HTTP response headers. Each header is placed on aline with its value, separated by a colon and a space. Each line is terminatedby a carriage return and line feed, and the bytestring is terminated with ablank line.In addition to their mapping interface and formatting features,
Headersobjects also have the following methods for querying and adding multi-valuedheaders, and for adding headers with MIME parameters:- 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 originalheader list or were added to this instance, and may contain duplicates. Anyfields deleted and re-inserted are always appended to the header list. If nofields exist with the given name, returns an empty list.
- add_header(name,value,**_params)¶
Add a (possibly multi-valued) header, with optional MIME parameters specifiedvia keyword arguments.
name is the header field to add. Keyword arguments can be used to set MIMEparameters for the header field. Each parameter must be a string or
None.Underscores in parameter names are converted to dashes, since dashes are illegalin Python identifiers, but many MIME parameter names include dashes. If theparameter value is a string, it is added to the header value parameters in theformname="value". If it isNone, only the parameter name is added.(This is used for MIME parameters without a value.) 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:headers parameter is optional.
wsgiref.simple_server – a simple WSGI HTTP server¶
This module implements a simple HTTP server (based onhttp.server)that serves WSGI applications. Each server instance serves a single WSGIapplication on a given host and port. If you want to serve multipleapplications on a single host and port, you should create a WSGI applicationthat parsesPATH_INFO to select which application to invoke for eachrequest. (E.g., using theshift_path_info() function fromwsgiref.util.)
- wsgiref.simple_server.make_server(host,port,app,server_class=WSGIServer,handler_class=WSGIRequestHandler)¶
Create a new WSGI server listening onhost andport, accepting connectionsforapp. The return value is an instance of the suppliedserver_class, andwill process requests using the specifiedhandler_class.app must be a WSGIapplication object, as defined byPEP 3333.
Example usage:
fromwsgiref.simple_serverimportmake_server,demo_appwithmake_server('',8000,demo_app)ashttpd:print("Serving HTTP on port 8000...")# Respond to requests until process is killedhttpd.serve_forever()# Alternative: serve one request, then exithttpd.handle_request()
- wsgiref.simple_server.demo_app(environ,start_response)¶
This function is a small but complete WSGI application that returns a text pagecontaining the message “Hello world!” and a list of the key/value pairs providedin theenviron parameter. It’s useful for verifying that a WSGI server (suchas
wsgiref.simple_server) is able to run a simple WSGI applicationcorrectly.Thestart_response callable should follow the
StartResponseprotocol.
- classwsgiref.simple_server.WSGIServer(server_address,RequestHandlerClass)¶
Create a
WSGIServerinstance.server_address should be a(host,port)tuple, andRequestHandlerClass should be the subclass ofhttp.server.BaseHTTPRequestHandlerthat will be used to processrequests.You do not normally need to call this constructor, as the
make_server()function can handle all the details for you.WSGIServeris a subclass ofhttp.server.HTTPServer, so allof its methods (such asserve_forever()andhandle_request()) areavailable.WSGIServeralso provides these WSGI-specific methods:- set_app(application)¶
Sets the callableapplication as the WSGI application that will receiverequests.
- 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.
- classwsgiref.simple_server.WSGIRequestHandler(request,client_address,server)¶
Create an HTTP handler for the givenrequest (i.e. a socket),client_address(a
(host,port)tuple), andserver (WSGIServerinstance).You do not need to create instances of this class directly; they areautomatically created as needed by
WSGIServerobjects. You can,however, subclass this class and supply it as ahandler_class to themake_server()function. Some possibly relevant methods for overriding insubclasses:- get_environ()¶
Return a
WSGIEnvironmentdictionary for arequest. The defaultimplementation copies the contents of theWSGIServerobject’sbase_environdictionary attribute and then adds various headers derivedfrom the HTTP request. Each call to this method should return a new dictionarycontaining all of the relevant CGI environment variables as specified inPEP 3333.
- get_stderr()¶
Return the object that should be used as the
wsgi.errorsstream. The defaultimplementation just returnssys.stderr.
- handle()¶
Process the HTTP request. The default implementation creates a handler instanceusing a
wsgiref.handlersclass to implement the actual WSGI applicationinterface.
wsgiref.validate — WSGI conformance checker¶
When creating new WSGI application objects, frameworks, servers, or middleware,it can be useful to validate the new code’s conformance usingwsgiref.validate. This module provides a function that creates WSGIapplication objects that validate communications between a WSGI server orgateway and a WSGI application object, to check both sides for protocolconformance.
Note that this utility does not guarantee completePEP 3333 compliance; anabsence of errors from this module does not necessarily mean that errors do notexist. However, if this module does produce an error, then it is virtuallycertain that either the server or application is not 100% compliant.
This module is based on thepaste.lint module from Ian Bicking’s “PythonPaste” library.
- wsgiref.validate.validator(application)¶
Wrapapplication and return a new WSGI application object. The returnedapplication will forward all requests to the originalapplication, and willcheck that both theapplication and the server invoking it are conforming tothe WSGI specification and toRFC 2616.
Any detected nonconformance results in an
AssertionErrorbeing raised;note, however, that how these errors are handled is server-dependent. Forexample,wsgiref.simple_serverand other servers based onwsgiref.handlers(that don’t override the error handling methods to dosomething else) will simply output a message that an error has occurred, anddump the traceback tosys.stderror some other error stream.This wrapper may also generate output using the
warningsmodule toindicate behaviors that are questionable but which may not actually beprohibited byPEP 3333. Unless they are suppressed using Python command-lineoptions or thewarningsAPI, any such warnings will be written tosys.stderr(notwsgi.errors, unless they happen to be the sameobject).Example usage:
fromwsgiref.validateimportvalidatorfromwsgiref.simple_serverimportmake_server# Our callable object which is intentionally not compliant to the# standard, so the validator is going to breakdefsimple_app(environ,start_response):status='200 OK'# HTTP Statusheaders=[('Content-type','text/plain')]# HTTP Headersstart_response(status,headers)# This is going to break because we need to return a list, and# the validator is going to inform usreturnb"Hello World"# This is the application wrapped in a validatorvalidator_app=validator(simple_app)withmake_server('',8000,validator_app)ashttpd:print("Listening on port 8000....")httpd.serve_forever()
wsgiref.handlers – server/gateway base classes¶
This module provides base handler classes for implementing WSGI servers andgateways. These base classes handle most of the work of communicating with aWSGI application, as long as they are given a CGI-like environment, along withinput, output, and error streams.
- classwsgiref.handlers.CGIHandler¶
CGI-based invocation via
sys.stdin,sys.stdout,sys.stderrandos.environ. This is useful when you have a WSGI application and want to runit as a CGI script. Simply invokeCGIHandler().run(app), whereappisthe WSGI application object you wish to invoke.This class is a subclass of
BaseCGIHandlerthat setswsgi.run_onceto true,wsgi.multithreadto false, andwsgi.multiprocessto true, andalways usessysandosto obtain the necessary CGI streams andenvironment.
- classwsgiref.handlers.IISCGIHandler¶
A specialized alternative to
CGIHandler, for use when deploying onMicrosoft’s IIS web server, without having set the config allowPathInfooption (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7).By default, IIS gives a
PATH_INFOthat duplicates theSCRIPT_NAMEatthe front, causing problems for WSGI applications that wish to implementrouting. This handler strips any such duplicated path.IIS can be configured to pass the correct
PATH_INFO, but this causesanother bug wherePATH_TRANSLATEDis wrong. Luckily this variable israrely used and is not guaranteed by WSGI. On IIS<7, though, thesetting can only be made on a vhost level, affecting all other scriptmappings, many of which break when exposed to thePATH_TRANSLATEDbug.For this reason IIS<7 is almost never deployed with the fix (Even IIS7rarely uses it because there is still no UI for it.).There is no way for CGI code to tell whether the option was set, so aseparate handler class is provided. It is used in the same way as
CGIHandler, i.e., by callingIISCGIHandler().run(app), whereappis the WSGI application object you wish to invoke.Added in version 3.2.
- classwsgiref.handlers.BaseCGIHandler(stdin,stdout,stderr,environ,multithread=True,multiprocess=False)¶
Similar to
CGIHandler, but instead of using thesysandosmodules, the CGI environment and I/O streams are specified explicitly.Themultithread andmultiprocess values are used to set thewsgi.multithreadandwsgi.multiprocessflags for any applications run bythe handler instance.This class is a subclass of
SimpleHandlerintended for use withsoftware other than HTTP “origin servers”. If you are writing a gatewayprotocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses aStatus:header to send an HTTP status, you probably want to subclass thisinstead ofSimpleHandler.
- classwsgiref.handlers.SimpleHandler(stdin,stdout,stderr,environ,multithread=True,multiprocess=False)¶
Similar to
BaseCGIHandler, but designed for use with HTTP originservers. If you are writing an HTTP server implementation, you will probablywant to subclass this instead ofBaseCGIHandler.This class is a subclass of
BaseHandler. It overrides the__init__(),get_stdin(),get_stderr(),add_cgi_vars(),_write(), and_flush()methods tosupport explicitly setting theenvironment and streams via the constructor. The supplied environment andstreams are stored in thestdin,stdout,stderr, andenvironattributes.The
write()method ofstdout should writeeach chunk in full, likeio.BufferedIOBase.
- classwsgiref.handlers.BaseHandler¶
This is an abstract base class for running WSGI applications. Each instancewill handle a single HTTP request, although in principle you could create asubclass that was reusable for multiple requests.
BaseHandlerinstances have only one method intended for external use:- run(app)¶
Run the specified WSGI application,app.
All of the other
BaseHandlermethods are invoked by this method in theprocess of running the application, and thus exist primarily to allowcustomizing the process.The following methods MUST be overridden in a subclass:
- _write(data)¶
Buffer the bytesdata for transmission to the client. It’s okay if thismethod actually transmits the data;
BaseHandlerjust separates writeand flush operations for greater efficiency when the underlying system actuallyhas such a distinction.
- _flush()¶
Force buffered data to be transmitted to the client. It’s okay if this methodis a no-op (i.e., if
_write()actually sends the data).
- get_stdin()¶
Return an object compatible with
InputStreamsuitable for use as thewsgi.inputof therequest currently being processed.
- get_stderr()¶
Return an object compatible with
ErrorStreamsuitable for use as thewsgi.errorsof therequest currently being processed.
- add_cgi_vars()¶
Insert CGI variables for the current request into the
environattribute.
Here are some other methods and attributes you may wish to override. This listis only a summary, however, and does not include every method that can beoverridden. You should consult the docstrings and source code for additionalinformation before attempting to create a customized
BaseHandlersubclass.Attributes and methods for customizing the WSGI environment:
- wsgi_multithread¶
The value to be used for the
wsgi.multithreadenvironment variable. Itdefaults to true inBaseHandler, but may have a different default (orbe set by the constructor) in the other subclasses.
- wsgi_multiprocess¶
The value to be used for the
wsgi.multiprocessenvironment variable. Itdefaults to true inBaseHandler, but may have a different default (orbe set by the constructor) in the other subclasses.
- wsgi_run_once¶
The value to be used for the
wsgi.run_onceenvironment variable. Itdefaults to false inBaseHandler, butCGIHandlersets it totrue by default.
- os_environ¶
The default environment variables to be included in every request’s WSGIenvironment. By default, this is a copy of
os.environat the time thatwsgiref.handlerswas imported, but subclasses can either create their ownat the class or instance level. Note that the dictionary should be consideredread-only, since the default value is shared between multiple classes andinstances.
- server_software¶
If the
origin_serverattribute is set, this attribute’s value is used toset the defaultSERVER_SOFTWAREWSGI environment variable, and also to set adefaultServer:header in HTTP responses. It is ignored for handlers (suchasBaseCGIHandlerandCGIHandler) that are not HTTP originservers.Changed in version 3.3:The term “Python” is replaced with implementation specific term like“CPython”, “Jython” etc.
- get_scheme()¶
Return the URL scheme being used for the current request. The defaultimplementation uses the
guess_scheme()function fromwsgiref.utilto guess whether the scheme should be “http” or “https”, based on the currentrequest’senvironvariables.
- setup_environ()¶
Set the
environattribute to a fully populated WSGI environment. Thedefault implementation uses all of the above methods and attributes, plus theget_stdin(),get_stderr(), andadd_cgi_vars()methods and thewsgi_file_wrapperattribute. It also inserts aSERVER_SOFTWAREkeyif not present, as long as theorigin_serverattribute is a true valueand theserver_softwareattribute is set.
Methods and attributes for customizing exception handling:
- log_exception(exc_info)¶
Log theexc_info tuple in the server log.exc_info is a
(type,value,traceback)tuple. The default implementation simply writes the traceback tothe request’swsgi.errorsstream and flushes it. Subclasses can overridethis method to change the format or retarget the output, mail the traceback toan 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. IfNone, all frames are included.
- error_output(environ,start_response)¶
This method is a WSGI application to generate an error page for the user. It isonly invoked if an error occurs before headers are sent to the client.
This method can access the current error using
sys.exception(),and should pass that information tostart_response when calling it (asdescribed in the “Error Handling” section ofPEP 3333). In particular,thestart_response callable should follow theStartResponseprotocol.The default implementation just uses the
error_status,error_headers, anderror_bodyattributes to generate an outputpage. Subclasses can override this to produce more dynamic error output.Note, however, that it’s not recommended from a security perspective to spit outdiagnostics to any old user; ideally, you should have to do something special toenable diagnostic output, which is why the default implementation doesn’tinclude any.
- error_status¶
The HTTP status used for error responses. This should be a status string asdefined inPEP 3333; it defaults to a 500 code and message.
- error_headers¶
The HTTP headers used for error responses. This should be a list of WSGIresponse headers (
(name,value)tuples), as described inPEP 3333. Thedefault list just sets the content type totext/plain.
- error_body¶
The error response body. This should be an HTTP response body bytestring. Itdefaults to the plain text, “A server error occurred. Please contact theadministrator.”
Methods and attributes forPEP 3333’s “Optional Platform-Specific FileHandling” feature:
- wsgi_file_wrapper¶
A
wsgi.file_wrapperfactory, compatible withwsgiref.types.FileWrapper, orNone. The default valueof this attribute is thewsgiref.util.FileWrapperclass.
- sendfile()¶
Override to implement platform-specific file transmission. This method iscalled only if the application’s return value is an instance of the classspecified by the
wsgi_file_wrapperattribute. It should return a truevalue if it was able to successfully transmit the file, so that the defaulttransmission code will not be executed. The default implementation of thismethod 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 thanvia a CGI-like gateway protocol that wants the HTTP status in a specialStatus:header.This attribute’s default value is true in
BaseHandler, but false inBaseCGIHandlerandCGIHandler.
- http_version¶
If
origin_serveris true, this string attribute is used to set the HTTPversion of the response set to the client. It defaults to"1.0".
- wsgiref.handlers.read_environ()¶
Transcode CGI variables from
os.environtoPEP 3333 “bytes in unicode”strings, returning a new dictionary. This function is used byCGIHandlerandIISCGIHandlerin place of directly usingos.environ, which is not necessarily WSGI-compliant on all platformsand web servers using Python 3 – specifically, ones where the OS’sactual environment is Unicode (i.e. Windows), or ones where the environmentis bytes, but the system encoding used by Python to decode it is anythingother than ISO-8859-1 (e.g. Unix systems using UTF-8).If you are implementing a CGI-based handler of your own, you probably wantto use this routine instead of just copying values out of
os.environdirectly.Added in version 3.2.
wsgiref.types – WSGI types for static type checking¶
This module provides various types for static type checking as describedinPEP 3333.
Added in version 3.11.
- classwsgiref.types.StartResponse¶
A
typing.Protocoldescribingstart_response()callables (PEP 3333).
- wsgiref.types.WSGIEnvironment¶
A type alias describing a WSGI environment dictionary.
- wsgiref.types.WSGIApplication¶
A type alias describing a WSGI application callable.
- classwsgiref.types.InputStream¶
A
typing.Protocoldescribing aWSGI Input Stream.
- classwsgiref.types.ErrorStream¶
A
typing.Protocoldescribing aWSGI Error Stream.
- classwsgiref.types.FileWrapper¶
A
typing.Protocoldescribing afile wrapper.Seewsgiref.util.FileWrapperfor a concrete implementation of thisprotocol.
Examples¶
This is a working “Hello World” WSGI application, where thestart_responsecallable should follow theStartResponse protocol:
"""Every WSGI application must have an application object - a callableobject that accepts two arguments. For that purpose, we're going touse a function (note that you're not limited to a function, you canuse a class for example). The first argument passed to the functionis a dictionary containing CGI-style environment variables and thesecond variable is the callable object."""fromwsgiref.simple_serverimportmake_serverdefhello_world_app(environ,start_response):status="200 OK"# HTTP Statusheaders=[("Content-type","text/plain; charset=utf-8")]# HTTP Headersstart_response(status,headers)# The returned object is going to be printedreturn[b"Hello World"]withmake_server("",8000,hello_world_app)ashttpd:print("Serving on port 8000...")# Serve until process is killedhttpd.serve_forever()
Example of a WSGI application serving the current directory, accept optionaldirectory and port number (default: 8000) on the command line:
"""Small wsgiref based web server. Takes a path to serve from and anoptional port number (defaults to 8000), then tries to serve files.MIME types are guessed from the file names, 404 errors are raisedif the file is not found."""importmimetypesimportosimportsysfromwsgirefimportsimple_server,utildefapp(environ,respond):# Get the file name and MIME typefn=os.path.join(path,environ["PATH_INFO"][1:])if"."notinfn.split(os.path.sep)[-1]:fn=os.path.join(fn,"index.html")mime_type=mimetypes.guess_file_type(fn)[0]# Return 200 OK if file exists, otherwise 404 Not Foundifos.path.exists(fn):respond("200 OK",[("Content-Type",mime_type)])returnutil.FileWrapper(open(fn,"rb"))else:respond("404 Not Found",[("Content-Type","text/plain")])return[b"not found"]if__name__=="__main__":# Get the path and port from command-line argumentspath=sys.argv[1]iflen(sys.argv)>1elseos.getcwd()port=int(sys.argv[2])iflen(sys.argv)>2else8000# Make and start the server until control-chttpd=simple_server.make_server("",port,app)print(f"Serving{path} on port{port}, control-C to stop")try:httpd.serve_forever()exceptKeyboardInterrupt:print("Shutting down.")httpd.server_close()