Opens the specified key, returning a handle object.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that identifies the sub_key to open.
reserved is a reserved integer, and must be zero. The default is zero.
access is an integer that specifies an access mask that describes the desired security access for the key. Default is KEY_READ. See Access Rights for other allowed values.
The result is a new handle to the specified key.
If the function fails, OSError is raised.
Raises an auditing event winreg.OpenKey with arguments key, sub_key, access.
Raises an auditing event winreg.OpenKey/result with argument key.
Changed in version 3.2: Allow the use of named arguments.
Changed in version 3.3: See above.


Closes the underlying Windows handle.
If the handle is already closed, no error is raised.


Detaches the Windows handle from the handle object.
The result is an integer that holds the value of the handle before it is detached. If the handle is already detached or closed, this will return zero.
After calling this function, the handle is effectively invalidated, but the handle is not closed. You would call this function when you need the underlying Win32 handle to exist beyond the lifetime of the handle object.
Raises an auditing event winreg.PyHKEY.Detach with argument key.


The HKEY object implements __enter__() and __exit__() and thus supports the context protocol for the with statement:
will automatically close key when control leaves the with block.


Returns information about a key, as a tuple.
key is an already open key, or one of the predefined HKEY_* constants.
The result is a tuple of 3 items:
Index
Meaning
0
An integer giving the number of sub keys this key has.
1
An integer giving the number of values this key has.
2
An integer giving when the key was last modified (if available) as 100’s of nanoseconds since Jan 1, 1601.
Raises an auditing event winreg.QueryInfoKey with argument key.


Determines the reflection state for the specified key.
key is an already open key, or one of the predefined HKEY_* constants.
Returns True if reflection is disabled.
Will generally raise NotImplementedError if executed on a 32-bit operating system.
Raises an auditing event winreg.QueryReflectionKey with argument key.


Retrieves the unnamed value for a key, as a string.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that holds the name of the subkey with which the value is associated. If this parameter is None or empty, the function retrieves the value set by the SetValue() method for the key identified by key.
Values in the registry have name, type, and data components. This method retrieves the data for a key’s first value that has a NULL name. But the underlying API call doesn’t return the type, so always use QueryValueEx() if possible.
Raises an auditing event winreg.QueryValue with arguments key, sub_key, value_name.


Retrieves the type and data for a specified value name associated with an open registry key.
key is an already open key, or one of the predefined HKEY_* constants.
value_name is a string indicating the value to query.
The result is a tuple of 2 items:
Index
Meaning
0
The value of the registry item.
1
An integer giving the registry type for this value (see table in docs for SetValueEx())
Raises an auditing event winreg.QueryValue with arguments key, sub_key, value_name.


A 32-bit number in little-endian format. Equivalent to REG_DWORD.


Null-terminated string containing references to environment variables (%PATH%).


A sequence of null-terminated strings, terminated by two null characters. (Python handles this termination automatically.)


A 64-bit number in little-endian format. Equivalent to REG_QWORD.
New in version 3.6.


Saves the specified key, and all its subkeys to the specified file.
key is an already open key, or one of the predefined HKEY_* constants.
file_name is the name of the file to save registry data to. This file cannot already exist. If this filename includes an extension, it cannot be used on file allocation table (FAT) file systems by the LoadKey() method.
If key represents a key on a remote computer, the path described by file_name is relative to the remote computer. The caller of this method must possess the SeBackupPrivilege security privilege. Note that privileges are different than permissions – see the Conflicts Between User Rights and Permissions documentation for more details.
This function passes NULL for security_attributes to the API.
Raises an auditing event winreg.SaveKey with arguments key, file_name.


Associates a value with a specified key.
key is an already open key, or one of the predefined HKEY_* constants.
sub_key is a string that names the subkey with which the value is associated.
type is an integer that specifies the type of the data. Currently this must be REG_SZ, meaning only strings are supported. Use the SetValueEx() function for support for other data types.
value is a string that specifies the new value.
If the key specified by the sub_key parameter does not exist, the SetValue function creates it.
Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.
The key identified by the key parameter must have been opened with KEY_SET_VALUE access.
Raises an auditing event winreg.SetValue with arguments key, sub_key, type, value.


Stores data in the value field of an open registry key.
key is an already open key, or one of the predefined HKEY_* constants.
value_name is a string that names the subkey with which the value is associated.
reserved can be anything – zero is always passed to the API.
type is an integer that specifies the type of the data. See Value Types for the available types.
value is a string that specifies the new value.
This method can also set additional value and type information for the specified key. The key identified by the key parameter must have been opened with KEY_SET_VALUE access.
To open the key, use the CreateKey() or OpenKey() methods.
Value lengths are limited by available memory. Long values (more than 2048 bytes) should be stored as files with the filenames stored in the configuration registry. This helps the registry perform efficiently.
Raises an auditing event winreg.SetValue with arguments key, sub_key, type, value.


The winsound module provides access to the basic sound-playing machinery provided by Windows platforms. It includes functions and several constants.
Beep the PC’s speaker. The frequency parameter specifies frequency, in hertz, of the sound, and must be in the range 37 through 32,767. The duration parameter specifies the number of milliseconds the sound should last. If the system is not able to beep the speaker, RuntimeError is raised.
Call the underlying PlaySound() function from the Platform API. The sound parameter may be a filename, a system sound alias, audio data as a bytes-like object, or None. Its interpretation depends on the value of flags, which can be a bitwise ORed combination of the constants described below. If the sound parameter is None, any currently playing waveform sound is stopped. If the system indicates an error, RuntimeError is raised.
Call the underlying MessageBeep() function from the Platform API. This plays a sound as specified in the registry. The type argument specifies which sound to play; possible values are -1, MB_ICONASTERISK, MB_ICONEXCLAMATION, MB_ICONHAND, MB_ICONQUESTION, and MB_OK, all described below. The value -1 produces a “simple beep”; this is the final fallback if a sound cannot be played otherwise. If the system indicates an error, RuntimeError is raised.
The sound parameter is the name of a WAV file. Do not use with SND_ALIAS.
The sound parameter is a sound association name from the registry. If the registry contains no such name, play the system default sound unless SND_NODEFAULT is also specified. If no default sound is registered, raise RuntimeError. Do not use with SND_FILENAME.
All Win32 systems support at least the following; most systems support many more:
PlaySound() name
Corresponding Control Panel Sound name
'SystemAsterisk'
Asterisk
'SystemExclamation'
Exclamation
'SystemExit'
Exit Windows
'SystemHand'
Critical Stop
'SystemQuestion'
Question
For example:
Play the sound repeatedly. The SND_ASYNC flag must also be used to avoid blocking. Cannot be used with SND_MEMORY.
The sound parameter to PlaySound() is a memory image of a WAV file, as a bytes-like object.
Note
This module does not support playing from a memory image asynchronously, so a combination of this flag and SND_ASYNC will raise RuntimeError.
Stop playing all instances of the specified sound.
Note
This flag is not supported on modern Windows platforms.
Return immediately, allowing sounds to play asynchronously.
If the specified sound cannot be found, do not play the system default sound.
Do not interrupt sounds currently playing.
Return immediately if the sound driver is busy.
Note
This flag is not supported on modern Windows platforms.
Play the SystemDefault sound.
Play the SystemExclamation sound.
Play the SystemHand sound.
Play the SystemQuestion sound.
Play the SystemDefault sound.


Beep the PC’s speaker. The frequency parameter specifies frequency, in hertz, of the sound, and must be in the range 37 through 32,767. The duration parameter specifies the number of milliseconds the sound should last. If the system is not able to beep the speaker, RuntimeError is raised.


Call the underlying MessageBeep() function from the Platform API. This plays a sound as specified in the registry. The type argument specifies which sound to play; possible values are -1, MB_ICONASTERISK, MB_ICONEXCLAMATION, MB_ICONHAND, MB_ICONQUESTION, and MB_OK, all described below. The value -1 produces a “simple beep”; this is the final fallback if a sound cannot be played otherwise. If the system indicates an error, RuntimeError is raised.


Call the underlying PlaySound() function from the Platform API. The sound parameter may be a filename, a system sound alias, audio data as a bytes-like object, or None. Its interpretation depends on the value of flags, which can be a bitwise ORed combination of the constants described below. If the sound parameter is None, any currently playing waveform sound is stopped. If the system indicates an error, RuntimeError is raised.


The sound parameter is a sound association name from the registry. If the registry contains no such name, play the system default sound unless SND_NODEFAULT is also specified. If no default sound is registered, raise RuntimeError. Do not use with SND_FILENAME.
All Win32 systems support at least the following; most systems support many more:
PlaySound() name
Corresponding Control Panel Sound name
'SystemAsterisk'
Asterisk
'SystemExclamation'
Exclamation
'SystemExit'
Exit Windows
'SystemHand'
Critical Stop
'SystemQuestion'
Question
For example:


Return immediately, allowing sounds to play asynchronously.


The sound parameter is the name of a WAV file. Do not use with SND_ALIAS.


Play the sound repeatedly. The SND_ASYNC flag must also be used to avoid blocking. Cannot be used with SND_MEMORY.


The sound parameter to PlaySound() is a memory image of a WAV file, as a bytes-like object.
Note
This module does not support playing from a memory image asynchronously, so a combination of this flag and SND_ASYNC will raise RuntimeError.


If the specified sound cannot be found, do not play the system default sound.


Do not interrupt sounds currently playing.


Return immediately if the sound driver is busy.
Note
This flag is not supported on modern Windows platforms.


Stop playing all instances of the specified sound.
Note
This flag is not supported on modern Windows platforms.


The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. Having a standard interface makes it easy to use an application that supports WSGI with a number of different web servers.
Only authors of web servers and programming frameworks need to know every detail and corner case of the WSGI design. 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.
wsgiref is a reference implementation of the WSGI specification that can be used to add WSGI support to a web server or framework. 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).
See wsgi.readthedocs.io for more information about WSGI, and links to tutorials and other resources.
This module provides a variety of utility functions for working with WSGI environments. A WSGI environment is a dictionary containing HTTP request variables as described in 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.
Return a guess for whether wsgi.url_scheme should be “http” or “https”, by checking for a HTTPS environment variable in the environ dictionary. 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. Typically, servers providing such protocols will include a HTTPS variable with a value of “1”, “yes”, or “on” when a request is received via SSL. So, this function returns “https” if such a value is found, and “http” otherwise.
Return the full request URI, optionally including the query string, using the algorithm found in the “URL Reconstruction” section of PEP 3333. If include_query is false, the query string is not included in the resulting URI.
Similar to request_uri(), except that the PATH_INFO and QUERY_STRING variables are ignored. The result is the base URI of the application object addressed by the request.
Shift a single name from PATH_INFO to SCRIPT_NAME and return the name. The environ dictionary is modified in-place; use a copy if you need to keep the original PATH_INFO or SCRIPT_NAME intact.
If there are no remaining path segments in PATH_INFO, None is 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 routine modifies the passed-in environment to make it suitable for invoking another WSGI application that is located at the target URI. 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 calls shift_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. That is, SCRIPT_NAME will change from /foo to /foo/bar, and PATH_INFO will change from /bar/baz to /baz.
When PATH_INFO is just a “/”, this routine returns an empty string and appends a trailing slash to SCRIPT_NAME, even though empty path segments are normally ignored, and SCRIPT_NAME doesn’t normally end in a slash. 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.
Update environ 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 the PEP 3333-defined wsgi.* variables. 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. It should NOT be used by actual WSGI servers or applications, since the data is fake!
Example usage:
In addition to the environment functions above, the wsgiref.util module also provides these miscellaneous utilities:
Return True if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by RFC 2616.
A wrapper to convert a file-like object to an iterator. The resulting objects support both __getitem__() and __iter__() iteration styles, for compatibility with Python 2.1 and Jython. As the object is iterated over, the optional blksize parameter will be repeatedly passed to the filelike object’s read() method to obtain bytestrings to yield. When read() returns an empty bytestring, iteration is ended and is not resumable.
If filelike has a close() method, the returned object will also have a close() method, and it will invoke the filelike object’s close() method when called.
Example usage:
Deprecated since version 3.8: Support for sequence protocol is deprecated.
This module provides a single class, Headers, for convenient manipulation of WSGI response headers using a mapping-like interface.
Create a mapping-like object wrapping headers, which must be a list of header name/value tuples as described in PEP 3333. The default value of headers is an empty list.
Headers objects support typical mapping operations including __getitem__(), get(), __setitem__(), setdefault(), __delitem__() and __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. Getting a nonexistent header just returns None, and deleting a nonexistent header does nothing.
Headers objects also support keys(), values(), and items() methods. The lists returned by keys() and items() can include the same key more than once if there is a multi-valued header. The len() of a Headers object is the same as the length of its items(), which is the same as the length of the wrapped header list. In fact, the items() method just returns a copy of the wrapped header list.
Calling bytes() on a Headers object returns a formatted bytestring suitable for transmission as HTTP response headers. 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.
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:
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 a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments.
name is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or None. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form name="value". If it is None, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage:
The above will add a header that looks like this:
Changed in version 3.5: headers parameter is optional.
This module implements a simple HTTP server (based on http.server) that serves WSGI applications. Each server instance serves a single WSGI application on a given host and port. If you want to serve multiple applications on a single host and port, you should create a WSGI application that parses PATH_INFO to select which application to invoke for each request. (E.g., using the shift_path_info() function from wsgiref.util.)
Create a new WSGI server listening on host and port, accepting connections for app. The return value is an instance of the supplied server_class, and will process requests using the specified handler_class. app must be a WSGI application object, as defined by PEP 3333.
Example usage:
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. It’s useful for verifying that a WSGI server (such as wsgiref.simple_server) is able to run a simple WSGI application correctly.
Create a WSGIServer instance. server_address should be a (host,port) tuple, and RequestHandlerClass should be the subclass of http.server.BaseHTTPRequestHandler that will be used to process requests.
You do not normally need to call this constructor, as the make_server() function can handle all the details for you.
WSGIServer is a subclass of http.server.HTTPServer, so all of its methods (such as serve_forever() and handle_request()) are available. WSGIServer also provides these WSGI-specific methods:
Sets the callable application as the WSGI application that will receive requests.
Returns the currently-set application callable.
Normally, however, you do not need to use these additional methods, as set_app() is normally called by make_server(), and the get_app() exists mainly for the benefit of request handler instances.
Create an HTTP handler for the given request (i.e. a socket), client_address (a (host,port) tuple), and server (WSGIServer instance).
You do not need to create instances of this class directly; they are automatically created as needed by WSGIServer objects. You can, however, subclass this class and supply it as a handler_class to the make_server() function. Some possibly relevant methods for overriding in subclasses:
Returns a dictionary containing the WSGI environment for a request. The default implementation copies the contents of the WSGIServer object’s base_environ dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in PEP 3333.
Return the object that should be used as the wsgi.errors stream. The default implementation just returns sys.stderr.
Process the HTTP request. The default implementation creates a handler instance using a wsgiref.handlers class to implement the actual WSGI application interface.
When creating new WSGI application objects, frameworks, servers, or middleware, it can be useful to validate the new code’s conformance using 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.
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. However, if this module does produce an error, then it is virtually certain that either the server or application is not 100% compliant.
This module is based on the paste.lint module from Ian Bicking’s “Python Paste” library.
Wrap application and return a new WSGI application object. 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.
Any detected nonconformance results in an AssertionError being raised; note, however, that how these errors are handled is server-dependent. For example, wsgiref.simple_server and other servers based on wsgiref.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 to sys.stderr or some other error stream.
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. Unless they are suppressed using Python command-line options or the warnings API, any such warnings will be written to sys.stderr (not wsgi.errors, unless they happen to be the same object).
Example usage:
This module provides base handler classes for implementing WSGI servers and gateways. 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.
CGI-based invocation via sys.stdin, sys.stdout, sys.stderr and os.environ. This is useful when you have a WSGI application and want to run it as a CGI script. Simply invoke CGIHandler().run(app), where app is the WSGI application object you wish to invoke.
This class is a subclass of BaseCGIHandler that sets wsgi.run_once to true, wsgi.multithread to false, and wsgi.multiprocess to true, and always uses sys and os to obtain the necessary CGI streams and environment.
A specialized alternative to CGIHandler, for use when deploying on Microsoft’s IIS web server, without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7).
By default, IIS gives a PATH_INFO that duplicates the SCRIPT_NAME at the front, causing problems for WSGI applications that wish to implement routing. This handler strips any such duplicated path.
IIS can be configured to pass the correct PATH_INFO, but this causes another bug where PATH_TRANSLATED is wrong. Luckily this variable is rarely used and is not guaranteed by 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 PATH_TRANSLATED bug. 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.).
There is no way for CGI code to tell whether the option was set, so a separate handler class is provided. It is used in the same way as CGIHandler, i.e., by calling IISCGIHandler().run(app), where app is the WSGI application object you wish to invoke.
New in version 3.2.
Similar to CGIHandler, but instead of using the sys and os modules, the CGI environment and I/O streams are specified explicitly. The multithread and multiprocess values are used to set the wsgi.multithread and wsgi.multiprocess flags for any applications run by the handler instance.
This class is a subclass of SimpleHandler intended for use with software other than HTTP “origin servers”. If you are writing a gateway protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a Status: header to send an HTTP status, you probably want to subclass this instead of SimpleHandler.
Similar to BaseCGIHandler, but designed for use with HTTP origin servers. If you are writing an HTTP server implementation, you will probably want to subclass this instead of BaseCGIHandler.
This class is a subclass of 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. The supplied environment and streams are stored in the stdin, stdout, stderr, and environ attributes.
The write() method of stdout should write each chunk in full, like io.BufferedIOBase.
This is an abstract base class for running WSGI applications. Each instance will handle a single HTTP request, although in principle you could create a subclass that was reusable for multiple requests.
BaseHandler instances have only one method intended for external use:
Run the specified WSGI application, 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.
The following methods MUST be overridden in a subclass:
Buffer the bytes data for transmission to the client. 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.
Force buffered data to be transmitted to the client. It’s okay if this method is a no-op (i.e., if _write() actually sends the data).
Return an input stream object suitable for use as the wsgi.input of the request currently being processed.
Return an output stream object suitable for use as the wsgi.errors of the request currently being processed.
Insert CGI variables for the current request into the environ attribute.
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.
Attributes and methods for customizing the WSGI environment:
The value to be used for the wsgi.multithread environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.
The value to be used for the wsgi.multiprocess environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.
The value to be used for the wsgi.run_once environment variable. It defaults to false in BaseHandler, but CGIHandler sets it to true by default.
The default environment variables to be included in every request’s WSGI environment. By default, this is a copy of os.environ at the time that wsgiref.handlers was imported, but subclasses can either create their own at the class or instance level. Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances.
If the origin_server attribute is set, this attribute’s value is used to set the default SERVER_SOFTWARE WSGI environment variable, and also to set a default Server: header in HTTP responses. It is ignored for handlers (such as BaseCGIHandler and CGIHandler) that are not HTTP origin servers.
Changed in version 3.3: The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc.
Return the URL scheme being used for the current request. The default implementation uses the guess_scheme() function from wsgiref.util to guess whether the scheme should be “http” or “https”, based on the current request’s environ variables.
Set the environ attribute to a fully-populated WSGI environment. The default implementation uses all of the above methods and attributes, plus the get_stdin(), get_stderr(), and add_cgi_vars() methods and the wsgi_file_wrapper attribute. It also inserts a SERVER_SOFTWARE key if not present, as long as the origin_server attribute is a true value and the server_software attribute is set.
Methods and attributes for customizing exception handling:
Log the exc_info tuple in the server log. exc_info is a (type, value,
traceback) tuple. The default implementation simply writes the traceback to the request’s wsgi.errors stream and flushes it. 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.
The maximum number of frames to include in tracebacks output by the default log_exception() method. If None, all frames are included.
This method is a WSGI application to generate an error page for the user. 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).
The default implementation just uses the error_status, error_headers, and error_body attributes to generate an output page. 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.
The HTTP status used for error responses. This should be a status string as defined in PEP 3333; it defaults to a 500 code and message.
The HTTP headers used for error responses. This should be a list of WSGI response headers ((name, value) tuples), as described in PEP 3333. The default list just sets the content type to text/plain.
The error response body. This should be an HTTP response body 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:
A wsgi.file_wrapper factory, or None. The default value of this attribute is the wsgiref.util.FileWrapper class.
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. 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. The default implementation of this method just returns a false value.
Miscellaneous methods and attributes:
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 special Status: header.
This attribute’s default value is true in BaseHandler, but false in BaseCGIHandler and CGIHandler.
If origin_server is true, this string attribute is used to set the HTTP version of the response set to the client. It defaults to "1.0".
Transcode CGI variables from os.environ to PEP 3333 “bytes in unicode” strings, returning a new dictionary. This function is used by CGIHandler and IISCGIHandler in place of directly using os.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).
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 os.environ directly.
New in version 3.2.
This is a working “Hello World” WSGI application:
Example of a WSGI application serving the current directory, accept optional directory and port number (default: 8000) on the command line:


Similar to CGIHandler, but instead of using the sys and os modules, the CGI environment and I/O streams are specified explicitly. The multithread and multiprocess values are used to set the wsgi.multithread and wsgi.multiprocess flags for any applications run by the handler instance.
This class is a subclass of SimpleHandler intended for use with software other than HTTP “origin servers”. If you are writing a gateway protocol implementation (such as CGI, FastCGI, SCGI, etc.) that uses a Status: header to send an HTTP status, you probably want to subclass this instead of SimpleHandler.


This is an abstract base class for running WSGI applications. Each instance will handle a single HTTP request, although in principle you could create a subclass that was reusable for multiple requests.
BaseHandler instances have only one method intended for external use:
Run the specified WSGI application, 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.
The following methods MUST be overridden in a subclass:
Buffer the bytes data for transmission to the client. 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.
Force buffered data to be transmitted to the client. It’s okay if this method is a no-op (i.e., if _write() actually sends the data).
Return an input stream object suitable for use as the wsgi.input of the request currently being processed.
Return an output stream object suitable for use as the wsgi.errors of the request currently being processed.
Insert CGI variables for the current request into the environ attribute.
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.
Attributes and methods for customizing the WSGI environment:
The value to be used for the wsgi.multithread environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.
The value to be used for the wsgi.multiprocess environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.
The value to be used for the wsgi.run_once environment variable. It defaults to false in BaseHandler, but CGIHandler sets it to true by default.
The default environment variables to be included in every request’s WSGI environment. By default, this is a copy of os.environ at the time that wsgiref.handlers was imported, but subclasses can either create their own at the class or instance level. Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances.
If the origin_server attribute is set, this attribute’s value is used to set the default SERVER_SOFTWARE WSGI environment variable, and also to set a default Server: header in HTTP responses. It is ignored for handlers (such as BaseCGIHandler and CGIHandler) that are not HTTP origin servers.
Changed in version 3.3: The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc.
Return the URL scheme being used for the current request. The default implementation uses the guess_scheme() function from wsgiref.util to guess whether the scheme should be “http” or “https”, based on the current request’s environ variables.
Set the environ attribute to a fully-populated WSGI environment. The default implementation uses all of the above methods and attributes, plus the get_stdin(), get_stderr(), and add_cgi_vars() methods and the wsgi_file_wrapper attribute. It also inserts a SERVER_SOFTWARE key if not present, as long as the origin_server attribute is a true value and the server_software attribute is set.
Methods and attributes for customizing exception handling:
Log the exc_info tuple in the server log. exc_info is a (type, value,
traceback) tuple. The default implementation simply writes the traceback to the request’s wsgi.errors stream and flushes it. 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.
The maximum number of frames to include in tracebacks output by the default log_exception() method. If None, all frames are included.
This method is a WSGI application to generate an error page for the user. 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).
The default implementation just uses the error_status, error_headers, and error_body attributes to generate an output page. 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.
The HTTP status used for error responses. This should be a status string as defined in PEP 3333; it defaults to a 500 code and message.
The HTTP headers used for error responses. This should be a list of WSGI response headers ((name, value) tuples), as described in PEP 3333. The default list just sets the content type to text/plain.
The error response body. This should be an HTTP response body 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:
A wsgi.file_wrapper factory, or None. The default value of this attribute is the wsgiref.util.FileWrapper class.
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. 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. The default implementation of this method just returns a false value.
Miscellaneous methods and attributes:
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 special Status: header.
This attribute’s default value is true in BaseHandler, but false in BaseCGIHandler and CGIHandler.
If origin_server is true, this string attribute is used to set the HTTP version of the response set to the client. It defaults to "1.0".


Insert CGI variables for the current request into the environ attribute.


The error response body. This should be an HTTP response body bytestring. It defaults to the plain text, “A server error occurred. Please contact the administrator.”


The HTTP headers used for error responses. This should be a list of WSGI response headers ((name, value) tuples), as described in PEP 3333. The default list just sets the content type to text/plain.


This method is a WSGI application to generate an error page for the user. 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).
The default implementation just uses the error_status, error_headers, and error_body attributes to generate an output page. 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.


The HTTP status used for error responses. This should be a status string as defined in PEP 3333; it defaults to a 500 code and message.


Return the URL scheme being used for the current request. The default implementation uses the guess_scheme() function from wsgiref.util to guess whether the scheme should be “http” or “https”, based on the current request’s environ variables.


Return an output stream object suitable for use as the wsgi.errors of the request currently being processed.


Return an input stream object suitable for use as the wsgi.input of the request currently being processed.


If origin_server is true, this string attribute is used to set the HTTP version of the response set to the client. It defaults to "1.0".


Log the exc_info tuple in the server log. exc_info is a (type, value,
traceback) tuple. The default implementation simply writes the traceback to the request’s wsgi.errors stream and flushes it. 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.


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 special Status: header.
This attribute’s default value is true in BaseHandler, but false in BaseCGIHandler and CGIHandler.


The default environment variables to be included in every request’s WSGI environment. By default, this is a copy of os.environ at the time that wsgiref.handlers was imported, but subclasses can either create their own at the class or instance level. Note that the dictionary should be considered read-only, since the default value is shared between multiple classes and instances.


Run the specified WSGI application, app.


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. 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. The default implementation of this method just returns a false value.


If the origin_server attribute is set, this attribute’s value is used to set the default SERVER_SOFTWARE WSGI environment variable, and also to set a default Server: header in HTTP responses. It is ignored for handlers (such as BaseCGIHandler and CGIHandler) that are not HTTP origin servers.
Changed in version 3.3: The term “Python” is replaced with implementation specific term like “CPython”, “Jython” etc.


Set the environ attribute to a fully-populated WSGI environment. The default implementation uses all of the above methods and attributes, plus the get_stdin(), get_stderr(), and add_cgi_vars() methods and the wsgi_file_wrapper attribute. It also inserts a SERVER_SOFTWARE key if not present, as long as the origin_server attribute is a true value and the server_software attribute is set.


The maximum number of frames to include in tracebacks output by the default log_exception() method. If None, all frames are included.


A wsgi.file_wrapper factory, or None. The default value of this attribute is the wsgiref.util.FileWrapper class.


The value to be used for the wsgi.multiprocess environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.


The value to be used for the wsgi.multithread environment variable. It defaults to true in BaseHandler, but may have a different default (or be set by the constructor) in the other subclasses.


The value to be used for the wsgi.run_once environment variable. It defaults to false in BaseHandler, but CGIHandler sets it to true by default.


Force buffered data to be transmitted to the client. It’s okay if this method is a no-op (i.e., if _write() actually sends the data).


Buffer the bytes data for transmission to the client. 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.


CGI-based invocation via sys.stdin, sys.stdout, sys.stderr and os.environ. This is useful when you have a WSGI application and want to run it as a CGI script. Simply invoke CGIHandler().run(app), where app is the WSGI application object you wish to invoke.
This class is a subclass of BaseCGIHandler that sets wsgi.run_once to true, wsgi.multithread to false, and wsgi.multiprocess to true, and always uses sys and os to obtain the necessary CGI streams and environment.


A specialized alternative to CGIHandler, for use when deploying on Microsoft’s IIS web server, without having set the config allowPathInfo option (IIS>=7) or metabase allowPathInfoForScriptMappings (IIS<7).
By default, IIS gives a PATH_INFO that duplicates the SCRIPT_NAME at the front, causing problems for WSGI applications that wish to implement routing. This handler strips any such duplicated path.
IIS can be configured to pass the correct PATH_INFO, but this causes another bug where PATH_TRANSLATED is wrong. Luckily this variable is rarely used and is not guaranteed by 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 PATH_TRANSLATED bug. 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.).
There is no way for CGI code to tell whether the option was set, so a separate handler class is provided. It is used in the same way as CGIHandler, i.e., by calling IISCGIHandler().run(app), where app is the WSGI application object you wish to invoke.
New in version 3.2.


Transcode CGI variables from os.environ to PEP 3333 “bytes in unicode” strings, returning a new dictionary. This function is used by CGIHandler and IISCGIHandler in place of directly using os.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).
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 os.environ directly.
New in version 3.2.


Similar to BaseCGIHandler, but designed for use with HTTP origin servers. If you are writing an HTTP server implementation, you will probably want to subclass this instead of BaseCGIHandler.
This class is a subclass of 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. The supplied environment and streams are stored in the stdin, stdout, stderr, and environ attributes.
The write() method of stdout should write each chunk in full, like io.BufferedIOBase.


Create a mapping-like object wrapping headers, which must be a list of header name/value tuples as described in PEP 3333. The default value of headers is an empty list.
Headers objects support typical mapping operations including __getitem__(), get(), __setitem__(), setdefault(), __delitem__() and __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. Getting a nonexistent header just returns None, and deleting a nonexistent header does nothing.
Headers objects also support keys(), values(), and items() methods. The lists returned by keys() and items() can include the same key more than once if there is a multi-valued header. The len() of a Headers object is the same as the length of its items(), which is the same as the length of the wrapped header list. In fact, the items() method just returns a copy of the wrapped header list.
Calling bytes() on a Headers object returns a formatted bytestring suitable for transmission as HTTP response headers. 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.
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:
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 a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments.
name is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or None. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form name="value". If it is None, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage:
The above will add a header that looks like this:
Changed in version 3.5: headers parameter is optional.


Add a (possibly multi-valued) header, with optional MIME parameters specified via keyword arguments.
name is the header field to add. Keyword arguments can be used to set MIME parameters for the header field. Each parameter must be a string or None. Underscores in parameter names are converted to dashes, since dashes are illegal in Python identifiers, but many MIME parameter names include dashes. If the parameter value is a string, it is added to the header value parameters in the form name="value". If it is None, only the parameter name is added. (This is used for MIME parameters without a value.) Example usage:
The above will add a header that looks like this:


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.


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. It’s useful for verifying that a WSGI server (such as wsgiref.simple_server) is able to run a simple WSGI application correctly.


Create a new WSGI server listening on host and port, accepting connections for app. The return value is an instance of the supplied server_class, and will process requests using the specified handler_class. app must be a WSGI application object, as defined by PEP 3333.
Example usage:


Create an HTTP handler for the given request (i.e. a socket), client_address (a (host,port) tuple), and server (WSGIServer instance).
You do not need to create instances of this class directly; they are automatically created as needed by WSGIServer objects. You can, however, subclass this class and supply it as a handler_class to the make_server() function. Some possibly relevant methods for overriding in subclasses:
Returns a dictionary containing the WSGI environment for a request. The default implementation copies the contents of the WSGIServer object’s base_environ dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in PEP 3333.
Return the object that should be used as the wsgi.errors stream. The default implementation just returns sys.stderr.
Process the HTTP request. The default implementation creates a handler instance using a wsgiref.handlers class to implement the actual WSGI application interface.


Returns a dictionary containing the WSGI environment for a request. The default implementation copies the contents of the WSGIServer object’s base_environ dictionary attribute and then adds various headers derived from the HTTP request. Each call to this method should return a new dictionary containing all of the relevant CGI environment variables as specified in PEP 3333.


Return the object that should be used as the wsgi.errors stream. The default implementation just returns sys.stderr.


Process the HTTP request. The default implementation creates a handler instance using a wsgiref.handlers class to implement the actual WSGI application interface.


Create a WSGIServer instance. server_address should be a (host,port) tuple, and RequestHandlerClass should be the subclass of http.server.BaseHTTPRequestHandler that will be used to process requests.
You do not normally need to call this constructor, as the make_server() function can handle all the details for you.
WSGIServer is a subclass of http.server.HTTPServer, so all of its methods (such as serve_forever() and handle_request()) are available. WSGIServer also provides these WSGI-specific methods:
Sets the callable application as the WSGI application that will receive requests.
Returns the currently-set application callable.
Normally, however, you do not need to use these additional methods, as set_app() is normally called by make_server(), and the get_app() exists mainly for the benefit of request handler instances.


Returns the currently-set application callable.


Sets the callable application as the WSGI application that will receive requests.


Similar to request_uri(), except that the PATH_INFO and QUERY_STRING variables are ignored. The result is the base URI of the application object addressed by the request.


A wrapper to convert a file-like object to an iterator. The resulting objects support both __getitem__() and __iter__() iteration styles, for compatibility with Python 2.1 and Jython. As the object is iterated over, the optional blksize parameter will be repeatedly passed to the filelike object’s read() method to obtain bytestrings to yield. When read() returns an empty bytestring, iteration is ended and is not resumable.
If filelike has a close() method, the returned object will also have a close() method, and it will invoke the filelike object’s close() method when called.
Example usage:
Deprecated since version 3.8: Support for sequence protocol is deprecated.


Return a guess for whether wsgi.url_scheme should be “http” or “https”, by checking for a HTTPS environment variable in the environ dictionary. 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. Typically, servers providing such protocols will include a HTTPS variable with a value of “1”, “yes”, or “on” when a request is received via SSL. So, this function returns “https” if such a value is found, and “http” otherwise.


Return True if ‘header_name’ is an HTTP/1.1 “Hop-by-Hop” header, as defined by RFC 2616.


Return the full request URI, optionally including the query string, using the algorithm found in the “URL Reconstruction” section of PEP 3333. If include_query is false, the query string is not included in the resulting URI.


Update environ 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 the PEP 3333-defined wsgi.* variables. 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. It should NOT be used by actual WSGI servers or applications, since the data is fake!
Example usage:


Shift a single name from PATH_INFO to SCRIPT_NAME and return the name. The environ dictionary is modified in-place; use a copy if you need to keep the original PATH_INFO or SCRIPT_NAME intact.
If there are no remaining path segments in PATH_INFO, None is 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 routine modifies the passed-in environment to make it suitable for invoking another WSGI application that is located at the target URI. 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 calls shift_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. That is, SCRIPT_NAME will change from /foo to /foo/bar, and PATH_INFO will change from /bar/baz to /baz.
When PATH_INFO is just a “/”, this routine returns an empty string and appends a trailing slash to SCRIPT_NAME, even though empty path segments are normally ignored, and SCRIPT_NAME doesn’t normally end in a slash. 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.


Wrap application and return a new WSGI application object. 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.
Any detected nonconformance results in an AssertionError being raised; note, however, that how these errors are handled is server-dependent. For example, wsgiref.simple_server and other servers based on wsgiref.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 to sys.stderr or some other error stream.
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. Unless they are suppressed using Python command-line options or the warnings API, any such warnings will be written to sys.stderr (not wsgi.errors, unless they happen to be the same object).
Example usage:


Source code: Lib/xdrlib.py
The xdrlib module supports the External Data Representation Standard as described in RFC 1014, written by Sun Microsystems, Inc. June 1987. It supports most of the data types described in the RFC.
The xdrlib module defines two classes, one for packing variables into XDR representation, and another for unpacking from XDR representation. There are also two exception classes.
Packer is the class for packing data into XDR representation. The Packer class is instantiated with no arguments.
Unpacker is the complementary class which unpacks XDR data values from a string buffer. The input buffer is given as data.
See also
This RFC defined the encoding of data which was XDR at the time this module was originally written. It has apparently been obsoleted by RFC 1832.
Newer RFC that provides a revised definition of XDR.
Packer instances have the following methods:
Returns the current pack buffer as a string.
Resets the pack buffer to the empty string.
In general, you can pack any of the most common XDR data types by calling the appropriate pack_type() method. Each method takes a single argument, the value to pack. The following simple data type packing methods are supported: pack_uint(), pack_int(), pack_enum(), pack_bool(), pack_uhyper(), and pack_hyper().
Packs the single-precision floating point number value.
Packs the double-precision floating point number value.
The following methods support packing strings, bytes, and opaque data:
Packs a fixed length string, s. n is the length of the string but it is not packed into the data buffer. The string is padded with null bytes if necessary to guaranteed 4 byte alignment.
Packs a fixed length opaque data stream, similarly to pack_fstring().
Packs a variable length string, s. The length of the string is first packed as an unsigned integer, then the string data is packed with pack_fstring().
Packs a variable length opaque data string, similarly to pack_string().
Packs a variable length byte stream, similarly to pack_string().
The following methods support packing arrays and lists:
Packs a list of homogeneous items. This method is useful for lists with an indeterminate size; i.e. the size is not available until the entire list has been walked. For each item in the list, an unsigned integer 1 is packed first, followed by the data value from the list. pack_item is the function that is called to pack the individual item. At the end of the list, an unsigned integer 0 is packed.
For example, to pack a list of integers, the code might appear like this:
Packs a fixed length list (array) of homogeneous items. n is the length of the list; it is not packed into the buffer, but a ValueError exception is raised if len(array) is not equal to n. As above, pack_item is the function used to pack each element.
Packs a variable length list of homogeneous items. First, the length of the list is packed as an unsigned integer, then each element is packed as in pack_farray() above.
The Unpacker class offers the following methods:
Resets the string buffer with the given data.
Returns the current unpack position in the data buffer.
Sets the data buffer unpack position to position. You should be careful about using get_position() and set_position().
Returns the current unpack data buffer as a string.
Indicates unpack completion. Raises an Error exception if all of the data has not been unpacked.
In addition, every data type that can be packed with a Packer, can be unpacked with an Unpacker. Unpacking methods are of the form unpack_type(), and take no arguments. They return the unpacked object.
Unpacks a single-precision floating point number.
Unpacks a double-precision floating point number, similarly to unpack_float().
In addition, the following methods unpack strings, bytes, and opaque data:
Unpacks and returns a fixed length string. n is the number of characters expected. Padding with null bytes to guaranteed 4 byte alignment is assumed.
Unpacks and returns a fixed length opaque data stream, similarly to unpack_fstring().
Unpacks and returns a variable length string. The length of the string is first unpacked as an unsigned integer, then the string data is unpacked with unpack_fstring().
Unpacks and returns a variable length opaque data string, similarly to unpack_string().
Unpacks and returns a variable length byte stream, similarly to unpack_string().
The following methods support unpacking arrays and lists:
Unpacks and returns a list of homogeneous items. The list is unpacked one element at a time by first unpacking an unsigned integer flag. If the flag is 1, then the item is unpacked and appended to the list. A flag of 0 indicates the end of the list. unpack_item is the function that is called to unpack the items.
Unpacks and returns (as a list) a fixed length array of homogeneous items. n is number of list elements to expect in the buffer. As above, unpack_item is the function used to unpack each element.
Unpacks and returns a variable length list of homogeneous items. First, the length of the list is unpacked as an unsigned integer, then each element is unpacked as in unpack_farray() above.
Exceptions in this module are coded as class instances:
The base exception class. Error has a single public attribute msg containing the description of the error.
Class derived from Error. Contains no additional instance variables.
Here is an example of how you would catch one of these exceptions:


Class derived from Error. Contains no additional instance variables.


The base exception class. Error has a single public attribute msg containing the description of the error.


Packer is the class for packing data into XDR representation. The Packer class is instantiated with no arguments.


Returns the current pack buffer as a string.


Packs a variable length list of homogeneous items. First, the length of the list is packed as an unsigned integer, then each element is packed as in pack_farray() above.


Packs a variable length byte stream, similarly to pack_string().


Packs the double-precision floating point number value.


Packs a fixed length list (array) of homogeneous items. n is the length of the list; it is not packed into the buffer, but a ValueError exception is raised if len(array) is not equal to n. As above, pack_item is the function used to pack each element.


Packs the single-precision floating point number value.


Packs a fixed length opaque data stream, similarly to pack_fstring().


Packs a fixed length string, s. n is the length of the string but it is not packed into the data buffer. The string is padded with null bytes if necessary to guaranteed 4 byte alignment.


Packs a list of homogeneous items. This method is useful for lists with an indeterminate size; i.e. the size is not available until the entire list has been walked. For each item in the list, an unsigned integer 1 is packed first, followed by the data value from the list. pack_item is the function that is called to pack the individual item. At the end of the list, an unsigned integer 0 is packed.
For example, to pack a list of integers, the code might appear like this:


Packs a variable length opaque data string, similarly to pack_string().


Packs a variable length string, s. The length of the string is first packed as an unsigned integer, then the string data is packed with pack_fstring().


Resets the pack buffer to the empty string.


Unpacker is the complementary class which unpacks XDR data values from a string buffer. The input buffer is given as data.


Indicates unpack completion. Raises an Error exception if all of the data has not been unpacked.


Returns the current unpack data buffer as a string.


Returns the current unpack position in the data buffer.


Resets the string buffer with the given data.


Sets the data buffer unpack position to position. You should be careful about using get_position() and set_position().


Unpacks and returns a variable length list of homogeneous items. First, the length of the list is unpacked as an unsigned integer, then each element is unpacked as in unpack_farray() above.


Unpacks and returns a variable length byte stream, similarly to unpack_string().


Unpacks a double-precision floating point number, similarly to unpack_float().


Unpacks and returns (as a list) a fixed length array of homogeneous items. n is number of list elements to expect in the buffer. As above, unpack_item is the function used to unpack each element.


Unpacks a single-precision floating point number.


Unpacks and returns a fixed length opaque data stream, similarly to unpack_fstring().


Unpacks and returns a fixed length string. n is the number of characters expected. Padding with null bytes to guaranteed 4 byte alignment is assumed.


Unpacks and returns a list of homogeneous items. The list is unpacked one element at a time by first unpacking an unsigned integer flag. If the flag is 1, then the item is unpacked and appended to the list. A flag of 0 indicates the end of the list. unpack_item is the function that is called to unpack the items.


Unpacks and returns a variable length opaque data string, similarly to unpack_string().


Unpacks and returns a variable length string. The length of the string is first unpacked as an unsigned integer, then the string data is unpacked with unpack_fstring().


Source code: Lib/xml/dom/__init__.py
The Document Object Model, or “DOM,” is a cross-language API from the World Wide Web Consortium (W3C) for accessing and modifying XML documents. A DOM implementation presents an XML document as a tree structure, or allows client code to build such a structure from scratch. It then gives access to the structure through a set of objects which provided well-known interfaces.
The DOM is extremely useful for random-access applications. SAX only allows you a view of one bit of the document at a time. If you are looking at one SAX element, you have no access to another. If you are looking at a text node, you have no access to a containing element. When you write a SAX application, you need to keep track of your program’s position in the document somewhere in your own code. SAX does not do it for you. Also, if you need to look ahead in the XML document, you are just out of luck.
Some applications are simply impossible in an event driven model with no access to a tree. Of course you could build some sort of tree yourself in SAX events, but the DOM allows you to avoid writing that code. The DOM is a standard tree representation for XML data.
The Document Object Model is being defined by the W3C in stages, or “levels” in their terminology. The Python mapping of the API is substantially based on the DOM Level 2 recommendation.
DOM applications typically start by parsing some XML into a DOM. How this is accomplished is not covered at all by DOM Level 1, and Level 2 provides only limited improvements: There is a DOMImplementation object class which provides access to Document creation methods, but no way to access an XML reader/parser/Document builder in an implementation-independent way. There is also no well-defined way to access these methods without an existing Document object. In Python, each DOM implementation will provide a function getDOMImplementation(). DOM Level 3 adds a Load/Store specification, which defines an interface to the reader, but this is not yet available in the Python standard library.
Once you have a DOM document object, you can access the parts of your XML document through its properties and methods. These properties are defined in the DOM specification; this portion of the reference manual describes the interpretation of the specification in Python.
The specification provided by the W3C defines the DOM API for Java, ECMAScript, and OMG IDL. The Python mapping defined here is based in large part on the IDL version of the specification, but strict compliance is not required (though implementations are free to support the strict mapping from IDL). See section Conformance for a detailed discussion of mapping requirements.
See also
The W3C recommendation upon which the Python DOM API is based.
The W3C recommendation for the DOM supported by xml.dom.minidom.
This specifies the mapping from OMG IDL to Python.
The xml.dom contains the following functions:
Register the factory function with the name name. The factory function should return an object which implements the DOMImplementation interface. The factory function can return the same object every time, or a new one for each call, as appropriate for the specific implementation (e.g. if that implementation supports some customization).
Return a suitable DOM implementation. The name is either well-known, the module name of a DOM implementation, or None. If it is not None, imports the corresponding module and returns a DOMImplementation object if the import succeeds. If no name is given, and if the environment variable PYTHON_DOM is set, this variable is used to find the implementation.
If name is not given, this examines the available implementations to find one with the required feature set. If no implementation can be found, raise an ImportError. The features list must be a sequence of (feature,
version) pairs which are passed to the hasFeature() method on available DOMImplementation objects.
Some convenience constants are also provided:
The value used to indicate that no namespace is associated with a node in the DOM. This is typically found as the namespaceURI of a node, or used as the namespaceURI parameter to a namespaces-specific method.
The namespace URI associated with the reserved prefix xml, as defined by Namespaces in XML (section 4).
The namespace URI for namespace declarations, as defined by Document Object Model (DOM) Level 2 Core Specification (section 1.1.8).
The URI of the XHTML namespace as defined by XHTML 1.0: The Extensible HyperText Markup Language (section 3.1.1).
In addition, xml.dom contains a base Node class and the DOM exception classes. The Node class provided by this module does not implement any of the methods or attributes defined by the DOM specification; concrete DOM implementations must provide those. The Node class provided as part of this module does provide the constants used for the nodeType attribute on concrete Node objects; they are located within the class rather than at the module level to conform with the DOM specifications.
The definitive documentation for the DOM is the DOM specification from the W3C.
Note that DOM attributes may also be manipulated as nodes instead of as simple strings. It is fairly rare that you must do this, however, so this usage is not yet documented.
Interface
Section
Purpose
DOMImplementation
DOMImplementation Objects
Interface to the underlying implementation.
Node
Node Objects
Base interface for most objects in a document.
NodeList
NodeList Objects
Interface for a sequence of nodes.
DocumentType
DocumentType Objects
Information about the declarations needed to process a document.
Document
Document Objects
Object which represents an entire document.
Element
Element Objects
Element nodes in the document hierarchy.
Attr
Attr Objects
Attribute value nodes on element nodes.
Comment
Comment Objects
Representation of comments in the source document.
Text
Text and CDATASection Objects
Nodes containing textual content from the document.
ProcessingInstruction
ProcessingInstruction Objects
Processing instruction representation.
An additional section describes the exceptions defined for working with the DOM in Python.
The DOMImplementation interface provides a way for applications to determine the availability of particular features in the DOM they are using. DOM Level 2 added the ability to create new Document and DocumentType objects using the DOMImplementation as well.
Return True if the feature identified by the pair of strings feature and version is implemented.
Return a new Document object (the root of the DOM), with a child Element object having the given namespaceUri and qualifiedName. The doctype must be a DocumentType object created by createDocumentType(), or None. In the Python DOM API, the first two arguments can also be None in order to indicate that no Element child is to be created.
Return a new DocumentType object that encapsulates the given qualifiedName, publicId, and systemId strings, representing the information contained in an XML document type declaration.
All of the components of an XML document are subclasses of Node.
An integer representing the node type. Symbolic constants for the types are on the Node object: ELEMENT_NODE, ATTRIBUTE_NODE, TEXT_NODE, CDATA_SECTION_NODE, ENTITY_NODE, PROCESSING_INSTRUCTION_NODE, COMMENT_NODE, DOCUMENT_NODE, DOCUMENT_TYPE_NODE, NOTATION_NODE. This is a read-only attribute.
The parent of the current node, or None for the document node. The value is always a Node object or None. For Element nodes, this will be the parent element, except for the root element, in which case it will be the Document object. For Attr nodes, this is always None. This is a read-only attribute.
A NamedNodeMap of attribute objects. Only elements have actual values for this; others provide None for this attribute. This is a read-only attribute.
The node that immediately precedes this one with the same parent. For instance the element with an end-tag that comes just before the self element’s start-tag. Of course, XML documents are made up of more than just elements so the previous sibling could be text, a comment, or something else. If this node is the first child of the parent, this attribute will be None. This is a read-only attribute.
The node that immediately follows this one with the same parent. See also previousSibling. If this is the last child of the parent, this attribute will be None. This is a read-only attribute.
A list of nodes contained within this node. This is a read-only attribute.
The first child of the node, if there are any, or None. This is a read-only attribute.
The last child of the node, if there are any, or None. This is a read-only attribute.
The part of the tagName following the colon if there is one, else the entire tagName. The value is a string.
The part of the tagName preceding the colon if there is one, else the empty string. The value is a string, or None.
The namespace associated with the element name. This will be a string or None. This is a read-only attribute.
This has a different meaning for each node type; see the DOM specification for details. You can always get the information you would get here from another property such as the tagName property for elements or the name property for attributes. For all node types, the value of this attribute will be either a string or None. This is a read-only attribute.
This has a different meaning for each node type; see the DOM specification for details. The situation is similar to that with nodeName. The value is a string or None.
Return True if the node has any attributes.
Return True if the node has any child nodes.
Return True if other refers to the same node as this node. This is especially useful for DOM implementations which use any sort of proxy architecture (because more than one object can refer to the same node).
Note
This is based on a proposed DOM Level 3 API which is still in the “working draft” stage, but this particular interface appears uncontroversial. Changes from the W3C will not necessarily affect this method in the Python DOM interface (though any new W3C API for this would also be supported).
Add a new child node to this node at the end of the list of children, returning newChild. If the node was already in the tree, it is removed first.
Insert a new child node before an existing child. It must be the case that refChild is a child of this node; if not, ValueError is raised. newChild is returned. If refChild is None, it inserts newChild at the end of the children’s list.
Remove a child node. oldChild must be a child of this node; if not, ValueError is raised. oldChild is returned on success. If oldChild will not be used further, its unlink() method should be called.
Replace an existing node with a new node. It must be the case that oldChild is a child of this node; if not, ValueError is raised.
Join adjacent text nodes so that all stretches of text are stored as single Text instances. This simplifies processing text from a DOM tree for many applications.
Clone this node. Setting deep means to clone all child nodes as well. This returns the clone.
A NodeList represents a sequence of nodes. These objects are used in two ways in the DOM Core recommendation: an Element object provides one as its list of child nodes, and the getElementsByTagName() and getElementsByTagNameNS() methods of Node return objects with this interface to represent query results.
The DOM Level 2 recommendation defines one method and one attribute for these objects:
Return the i’th item from the sequence, if there is one, or None. The index i is not allowed to be less than zero or greater than or equal to the length of the sequence.
The number of nodes in the sequence.
In addition, the Python DOM interface requires that some additional support is provided to allow NodeList objects to be used as Python sequences. All NodeList implementations must include support for __len__() and __getitem__(); this allows iteration over the NodeList in for statements and proper support for the len() built-in function.
If a DOM implementation supports modification of the document, the NodeList implementation must also support the __setitem__() and __delitem__() methods.
Information about the notations and entities declared by a document (including the external subset if the parser uses it and can provide the information) is available from a DocumentType object. The DocumentType for a document is available from the Document object’s doctype attribute; if there is no DOCTYPE declaration for the document, the document’s doctype attribute will be set to None instead of an instance of this interface.
DocumentType is a specialization of Node, and adds the following attributes:
The public identifier for the external subset of the document type definition. This will be a string or None.
The system identifier for the external subset of the document type definition. This will be a URI as a string, or None.
A string giving the complete internal subset from the document. This does not include the brackets which enclose the subset. If the document has no internal subset, this should be None.
The name of the root element as given in the DOCTYPE declaration, if present.
This is a NamedNodeMap giving the definitions of external entities. For entity names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no entities are defined.
This is a NamedNodeMap giving the definitions of notations. For notation names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no notations are defined.
A Document represents an entire XML document, including its constituent elements, attributes, processing instructions, comments etc. Remember that it inherits properties from Node.
The one and only root element of the document.
Create and return a new element node. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().
Create and return a new element with a namespace. The tagName may have a prefix. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().
Create and return a text node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree.
Create and return a comment node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree.
Create and return a processing instruction node containing the target and data passed as parameters. As with the other creation methods, this one does not insert the node into the tree.
Create and return an attribute node. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.
Create and return an attribute node with a namespace. The tagName may have a prefix. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.
Search for all descendants (direct children, children’s children, etc.) with a particular element type name.
Search for all descendants (direct children, children’s children, etc.) with a particular namespace URI and localname. The localname is the part of the namespace after the prefix.
Element is a subclass of Node, so inherits all the attributes of that class.
The element type name. In a namespace-using document it may have colons in it. The value is a string.
Same as equivalent method in the Document class.
Same as equivalent method in the Document class.
Return True if the element has an attribute named by name.
Return True if the element has an attribute named by namespaceURI and localName.
Return the value of the attribute named by name as a string. If no such attribute exists, an empty string is returned, as if the attribute had no value.
Return the Attr node for the attribute named by attrname.
Return the value of the attribute named by namespaceURI and localName as a string. If no such attribute exists, an empty string is returned, as if the attribute had no value.
Return an attribute value as a node, given a namespaceURI and localName.
Remove an attribute by name. If there is no matching attribute, a NotFoundErr is raised.
Remove and return oldAttr from the attribute list, if present. If oldAttr is not present, NotFoundErr is raised.
Remove an attribute by name. Note that it uses a localName, not a qname. No exception is raised if there is no matching attribute.
Set an attribute value from a string.
Add a new attribute node to the element, replacing an existing attribute if necessary if the name attribute matches. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised.
Add a new attribute node to the element, replacing an existing attribute if necessary if the namespaceURI and localName attributes match. If a replacement occurs, the old attribute node will be returned. If newAttr is already in use, InuseAttributeErr will be raised.
Set an attribute value from a string, given a namespaceURI and a qname. Note that a qname is the whole attribute name. This is different than above.
Attr inherits from Node, so inherits all its attributes.
The attribute name. In a namespace-using document it may include a colon.
The part of the name following the colon if there is one, else the entire name. This is a read-only attribute.
The part of the name preceding the colon if there is one, else the empty string.
The text value of the attribute. This is a synonym for the nodeValue attribute.
NamedNodeMap does not inherit from Node.
The length of the attribute list.
Return an attribute with a particular index. The order you get the attributes in is arbitrary but will be consistent for the life of a DOM. Each item is an attribute node. Get its value with the value attribute.
There are also experimental methods that give this class more mapping behavior. You can use them or you can use the standardized getAttribute*() family of methods on the Element objects.
Comment represents a comment in the XML document. It is a subclass of Node, but cannot have child nodes.
The content of the comment as a string. The attribute contains all characters between the leading <!-- and trailing -->, but does not include them.
The Text interface represents text in the XML document. If the parser and DOM implementation support the DOM’s XML extension, portions of the text enclosed in CDATA marked sections are stored in CDATASection objects. These two interfaces are identical, but provide different values for the nodeType attribute.
These interfaces extend the Node interface. They cannot have child nodes.
The content of the text node as a string.
Note
The use of a CDATASection node does not indicate that the node represents a complete CDATA marked section, only that the content of the node was part of a CDATA section. A single CDATA section may be represented by more than one node in the document tree. There is no way to determine whether two adjacent CDATASection nodes represent different CDATA marked sections.
Represents a processing instruction in the XML document; this inherits from the Node interface and cannot have child nodes.
The content of the processing instruction up to the first whitespace character. This is a read-only attribute.
The content of the processing instruction following the first whitespace character.
The DOM Level 2 recommendation defines a single exception, DOMException, and a number of constants that allow applications to determine what sort of error occurred. DOMException instances carry a code attribute that provides the appropriate value for the specific exception.
The Python DOM interface provides the constants, but also expands the set of exceptions so that a specific exception exists for each of the exception codes defined by the DOM. The implementations must raise the appropriate specific exception, each of which carries the appropriate value for the code attribute.
Base exception class used for all specific DOM exceptions. This exception class cannot be directly instantiated.
Raised when a specified range of text does not fit into a string. This is not known to be used in the Python DOM implementations, but may be received from DOM implementations not written in Python.
Raised when an attempt is made to insert a node where the node type is not allowed.
Raised when an index or size parameter to a method is negative or exceeds the allowed values.
Raised when an attempt is made to insert an Attr node that is already present elsewhere in the document.
Raised if a parameter or an operation is not supported on the underlying object.
This exception is raised when a string parameter contains a character that is not permitted in the context it’s being used in by the XML 1.0 recommendation. For example, attempting to create an Element node with a space in the element type name will cause this error to be raised.
Raised when an attempt is made to modify the type of a node.
Raised when an attempt is made to use an object that is not defined or is no longer usable.
If an attempt is made to change any object in a way that is not permitted with regard to the Namespaces in XML recommendation, this exception is raised.
Exception when a node does not exist in the referenced context. For example, NamedNodeMap.removeNamedItem() will raise this if the node passed in does not exist in the map.
Raised when the implementation does not support the requested type of object or operation.
This is raised if data is specified for a node which does not support data.
Raised on attempts to modify an object where modifications are not allowed (such as for read-only nodes).
Raised when an invalid or illegal string is specified.
Raised when a node is inserted in a different document than it currently belongs to, and the implementation does not support migrating the node from one document to the other.
The exception codes defined in the DOM recommendation map to the exceptions described above according to this table:
Constant
Exception
DOMSTRING_SIZE_ERR
DomstringSizeErr
HIERARCHY_REQUEST_ERR
HierarchyRequestErr
INDEX_SIZE_ERR
IndexSizeErr
INUSE_ATTRIBUTE_ERR
InuseAttributeErr
INVALID_ACCESS_ERR
InvalidAccessErr
INVALID_CHARACTER_ERR
InvalidCharacterErr
INVALID_MODIFICATION_ERR
InvalidModificationErr
INVALID_STATE_ERR
InvalidStateErr
NAMESPACE_ERR
NamespaceErr
NOT_FOUND_ERR
NotFoundErr
NOT_SUPPORTED_ERR
NotSupportedErr
NO_DATA_ALLOWED_ERR
NoDataAllowedErr
NO_MODIFICATION_ALLOWED_ERR
NoModificationAllowedErr
SYNTAX_ERR
SyntaxErr
WRONG_DOCUMENT_ERR
WrongDocumentErr
This section describes the conformance requirements and relationships between the Python DOM API, the W3C DOM recommendations, and the OMG IDL mapping for Python.
The IDL types used in the DOM specification are mapped to Python types according to the following table.
IDL Type
Python Type
boolean
bool or int
int
int
long int
int
unsigned int
int
DOMString
str or bytes
null
None
The mapping from OMG IDL to Python defines accessor functions for IDL attribute declarations in much the way the Java mapping does. Mapping the IDL declarations
yields three accessor functions: a “get” method for someValue (_get_someValue()), and “get” and “set” methods for anotherValue (_get_anotherValue() and _set_anotherValue()). The mapping, in particular, does not require that the IDL attributes are accessible as normal Python attributes: object.someValue is not required to work, and may raise an AttributeError.
The Python DOM API, however, does require that normal attribute access work. This means that the typical surrogates generated by Python IDL compilers are not likely to work, and wrapper objects may be needed on the client if the DOM objects are accessed via CORBA. While this does require some additional consideration for CORBA DOM clients, the implementers with experience using DOM over CORBA from Python do not consider this a problem. Attributes that are declared readonly may not restrict write access in all DOM implementations.
In the Python DOM API, accessor functions are not required. If provided, they should take the form defined by the Python IDL mapping, but these methods are considered unnecessary since the attributes are accessible directly from Python. “Set” accessors should never be provided for readonly attributes.
The IDL definitions do not fully embody the requirements of the W3C DOM API, such as the notion of certain objects, such as the return value of getElementsByTagName(), being “live”. The Python DOM API does not require implementations to enforce such requirements.


The part of the name following the colon if there is one, else the entire name. This is a read-only attribute.


The attribute name. In a namespace-using document it may include a colon.


The part of the name preceding the colon if there is one, else the empty string.


The text value of the attribute. This is a synonym for the nodeValue attribute.


The content of the comment as a string. The attribute contains all characters between the leading <!-- and trailing -->, but does not include them.


Create and return an attribute node. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.


Create and return an attribute node with a namespace. The tagName may have a prefix. This method does not associate the attribute node with any particular element. You must use setAttributeNode() on the appropriate Element object to use the newly created attribute instance.


Create and return a comment node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree.


Create and return a new element node. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().


Create and return a new element with a namespace. The tagName may have a prefix. The element is not inserted into the document when it is created. You need to explicitly insert it with one of the other methods such as insertBefore() or appendChild().


Create and return a processing instruction node containing the target and data passed as parameters. As with the other creation methods, this one does not insert the node into the tree.


Create and return a text node containing the data passed as a parameter. As with the other creation methods, this one does not insert the node into the tree.


The one and only root element of the document.


Search for all descendants (direct children, children’s children, etc.) with a particular element type name.


Search for all descendants (direct children, children’s children, etc.) with a particular namespace URI and localname. The localname is the part of the namespace after the prefix.


This is a NamedNodeMap giving the definitions of external entities. For entity names defined more than once, only the first definition is provided (others are ignored as required by the XML recommendation). This may be None if the information is not provided by the parser, or if no entities are defined.


A string giving the complete internal subset from the document. This does not include the brackets which enclose the subset. If the document has no internal subset, this should be None.


The name of the root element as given in the DOCTYPE declaration, if present.