doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
CookieJar.clear([domain[, path[, name]]])
Clear some cookies. If invoked without arguments, clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified domain and URL path are removed. If given three arguments, then the cookie with the specified domain, path and name is removed. Raises KeyError if no matching cookie exists. | python.library.http.cookiejar#http.cookiejar.CookieJar.clear |
CookieJar.clear_session_cookies()
Discard all session cookies. Discards all contained cookies that have a true discard attribute (usually because they had either no max-age or expires cookie-attribute, or an explicit discard cookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window. Note that the save() method won’t save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument. | python.library.http.cookiejar#http.cookiejar.CookieJar.clear_session_cookies |
CookieJar.extract_cookies(response, request)
Extract cookies from HTTP response and store them in the CookieJar, where allowed by policy. The CookieJar will look for allowable Set-Cookie and Set-Cookie2 headers in the response argument, and store cookies as appropriate (subject to the CookiePolicy.set_ok() method’s approval). The response object (usually the result of a call to urllib.request.urlopen(), or similar) should support an info() method, which returns an email.message.Message instance. The request object (usually a urllib.request.Request instance) must support the methods get_full_url(), get_host(), unverifiable(), and origin_req_host attribute, as documented by urllib.request. The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set. Changed in version 3.3: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed. | python.library.http.cookiejar#http.cookiejar.CookieJar.extract_cookies |
CookieJar.make_cookies(response, request)
Return sequence of Cookie objects extracted from response object. See the documentation for extract_cookies() for the interfaces required of the response and request arguments. | python.library.http.cookiejar#http.cookiejar.CookieJar.make_cookies |
CookieJar.set_cookie(cookie)
Set a Cookie, without checking with policy to see whether or not it should be set. | python.library.http.cookiejar#http.cookiejar.CookieJar.set_cookie |
CookieJar.set_cookie_if_ok(cookie, request)
Set a Cookie if policy says it’s OK to do so. | python.library.http.cookiejar#http.cookiejar.CookieJar.set_cookie_if_ok |
CookieJar.set_policy(policy)
Set the CookiePolicy instance to be used. | python.library.http.cookiejar#http.cookiejar.CookieJar.set_policy |
class http.cookiejar.CookiePolicy
This class is responsible for deciding whether each cookie should be accepted from / returned to the server. | python.library.http.cookiejar#http.cookiejar.CookiePolicy |
CookiePolicy.domain_return_ok(domain, request)
Return False if cookies should not be returned, given cookie domain. This method is an optimization. It removes the need for checking every cookie with a particular domain (which might involve reading many files). Returning true from domain_return_ok() and path_return_ok() leaves all the work to return_ok(). If domain_return_ok() returns true for the cookie domain, path_return_ok() is called for the cookie path. Otherwise, path_return_ok() and return_ok() are never called for that cookie domain. If path_return_ok() returns true, return_ok() is called with the Cookie object itself for a full check. Otherwise, return_ok() is never called for that cookie path. Note that domain_return_ok() is called for every cookie domain, not just for the request domain. For example, the function might be called with both ".example.com" and "www.example.com" if the request domain is "www.example.com". The same goes for path_return_ok(). The request argument is as documented for return_ok(). | python.library.http.cookiejar#http.cookiejar.CookiePolicy.domain_return_ok |
CookiePolicy.hide_cookie2
Don’t add Cookie2 header to requests (the presence of this header indicates to the server that we understand RFC 2965 cookies). | python.library.http.cookiejar#http.cookiejar.CookiePolicy.hide_cookie2 |
CookiePolicy.netscape
Implement Netscape protocol. | python.library.http.cookiejar#http.cookiejar.CookiePolicy.netscape |
CookiePolicy.path_return_ok(path, request)
Return False if cookies should not be returned, given cookie path. See the documentation for domain_return_ok(). | python.library.http.cookiejar#http.cookiejar.CookiePolicy.path_return_ok |
CookiePolicy.return_ok(cookie, request)
Return boolean value indicating whether cookie should be returned to server. cookie is a Cookie instance. request is an object implementing the interface defined by the documentation for CookieJar.add_cookie_header(). | python.library.http.cookiejar#http.cookiejar.CookiePolicy.return_ok |
CookiePolicy.rfc2965
Implement RFC 2965 protocol. | python.library.http.cookiejar#http.cookiejar.CookiePolicy.rfc2965 |
CookiePolicy.set_ok(cookie, request)
Return boolean value indicating whether cookie should be accepted from server. cookie is a Cookie instance. request is an object implementing the interface defined by the documentation for CookieJar.extract_cookies(). | python.library.http.cookiejar#http.cookiejar.CookiePolicy.set_ok |
class http.cookiejar.DefaultCookiePolicy(blocked_domains=None, allowed_domains=None, netscape=True, rfc2965=False, rfc2109_as_netscape=None, hide_cookie2=False, strict_domain=False, strict_rfc2965_unverifiable=True, strict_ns_unverifiable=False, strict_ns_domain=DefaultCookiePolicy.DomainLiberal, strict_ns_set_initial_dollar=False, strict_ns_set_path=False, secure_protocols=("https", "wss"))
Constructor arguments should be passed as keyword arguments only. blocked_domains is a sequence of domain names that we never accept cookies from, nor return cookies to. allowed_domains if not None, this is a sequence of the only domains for which we accept and return cookies. secure_protocols is a sequence of protocols for which secure cookies can be added to. By default https and wss (secure websocket) are considered secure protocols. For all other arguments, see the documentation for CookiePolicy and DefaultCookiePolicy objects. DefaultCookiePolicy implements the standard accept / reject rules for Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (ie. cookies received in a Set-Cookie header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off or rfc2109_as_netscape is True, RFC 2109 cookies are ‘downgraded’ by the CookieJar instance to Netscape cookies, by setting the version attribute of the Cookie instance to 0. DefaultCookiePolicy also provides some parameters to allow some fine-tuning of policy. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy |
DefaultCookiePolicy.allowed_domains()
Return None, or the sequence of allowed domains (as a tuple). | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.allowed_domains |
DefaultCookiePolicy.blocked_domains()
Return the sequence of blocked domains (as a tuple). | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.blocked_domains |
DefaultCookiePolicy.DomainLiberal
Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched off). | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainLiberal |
DefaultCookiePolicy.DomainRFC2965Match
When setting cookies, require a full RFC 2965 domain-match. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainRFC2965Match |
DefaultCookiePolicy.DomainStrict
Equivalent to DomainStrictNoDots|DomainStrictNonDomain. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainStrict |
DefaultCookiePolicy.DomainStrictNoDots
When setting cookies, the ‘host prefix’ must not contain a dot (eg. www.foo.bar.com can’t set a cookie for .bar.com, because www.foo contains a dot). | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainStrictNoDots |
DefaultCookiePolicy.DomainStrictNonDomain
Cookies that did not explicitly specify a domain cookie-attribute can only be returned to a domain equal to the domain that set the cookie (eg. spam.example.com won’t be returned cookies from example.com that had no domain cookie-attribute). | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.DomainStrictNonDomain |
DefaultCookiePolicy.is_blocked(domain)
Return whether domain is on the blacklist for setting or receiving cookies. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.is_blocked |
DefaultCookiePolicy.is_not_allowed(domain)
Return whether domain is not on the whitelist for setting or receiving cookies. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.is_not_allowed |
DefaultCookiePolicy.rfc2109_as_netscape
If true, request that the CookieJar instance downgrade RFC 2109 cookies (ie. cookies received in a Set-Cookie header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of the Cookie instance to 0. The default value is None, in which case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned off. Therefore, RFC 2109 cookies are downgraded by default. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.rfc2109_as_netscape |
DefaultCookiePolicy.set_allowed_domains(allowed_domains)
Set the sequence of allowed domains, or None. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.set_allowed_domains |
DefaultCookiePolicy.set_blocked_domains(blocked_domains)
Set the sequence of blocked domains. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.set_blocked_domains |
DefaultCookiePolicy.strict_domain
Don’t allow sites to set two-component domains with country-code top-level domains like .co.uk, .gov.uk, .co.nz.etc. This is far from perfect and isn’t guaranteed to work! | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_domain |
DefaultCookiePolicy.strict_ns_domain
Flags indicating how strict to be with domain-matching rules for Netscape cookies. See below for acceptable values. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_domain |
DefaultCookiePolicy.strict_ns_set_initial_dollar
Ignore cookies in Set-Cookie: headers that have names starting with '$'. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_set_initial_dollar |
DefaultCookiePolicy.strict_ns_set_path
Don’t allow setting cookies whose path doesn’t path-match request URI. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_set_path |
DefaultCookiePolicy.strict_ns_unverifiable
Apply RFC 2965 rules on unverifiable transactions even to Netscape cookies. | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_ns_unverifiable |
DefaultCookiePolicy.strict_rfc2965_unverifiable
Follow RFC 2965 rules on unverifiable transactions (usually, an unverifiable transaction is one resulting from a redirect or a request for an image hosted on another site). If this is false, cookies are never blocked on the basis of verifiability | python.library.http.cookiejar#http.cookiejar.DefaultCookiePolicy.strict_rfc2965_unverifiable |
class http.cookiejar.FileCookieJar(filename, delayload=None, policy=None)
policy is an object implementing the CookiePolicy interface. For the other arguments, see the documentation for the corresponding attributes. A CookieJar which can load cookies from, and perhaps save cookies to, a file on disk. Cookies are NOT loaded from the named file until either the load() or revert() method is called. Subclasses of this class are documented in section FileCookieJar subclasses and co-operation with web browsers. Changed in version 3.8: The filename parameter supports a path-like object. | python.library.http.cookiejar#http.cookiejar.FileCookieJar |
FileCookieJar.delayload
If true, load cookies lazily from disk. This attribute should not be assigned to. This is only a hint, since this only affects performance, not behaviour (unless the cookies on disk are changing). A CookieJar object may ignore it. None of the FileCookieJar classes included in the standard library lazily loads cookies. | python.library.http.cookiejar#http.cookiejar.FileCookieJar.delayload |
FileCookieJar.filename
Filename of default file in which to keep cookies. This attribute may be assigned to. | python.library.http.cookiejar#http.cookiejar.FileCookieJar.filename |
FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)
Load cookies from a file. Old cookies are kept unless overwritten by newly loaded ones. Arguments are as for save(). The named file must be in the format understood by the class, or LoadError will be raised. Also, OSError may be raised, for example if the file does not exist. Changed in version 3.3: IOError used to be raised, it is now an alias of OSError. | python.library.http.cookiejar#http.cookiejar.FileCookieJar.load |
FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)
Clear all cookies and reload cookies from a saved file. revert() can raise the same exceptions as load(). If there is a failure, the object’s state will not be altered. | python.library.http.cookiejar#http.cookiejar.FileCookieJar.revert |
FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)
Save cookies to a file. This base class raises NotImplementedError. Subclasses may leave this method unimplemented. filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None, ValueError is raised. ignore_discard: save even cookies set to be discarded. ignore_expires: save even cookies that have expired The file is overwritten if it already exists, thus wiping all the cookies it contains. Saved cookies can be restored later using the load() or revert() methods. | python.library.http.cookiejar#http.cookiejar.FileCookieJar.save |
exception http.cookiejar.LoadError
Instances of FileCookieJar raise this exception on failure to load cookies from a file. LoadError is a subclass of OSError. Changed in version 3.3: LoadError was made a subclass of OSError instead of IOError. | python.library.http.cookiejar#http.cookiejar.LoadError |
class http.cookiejar.LWPCookieJar(filename, delayload=None, policy=None)
A FileCookieJar that can load from and save cookies to disk in format compatible with the libwww-perl library’s Set-Cookie3 file format. This is convenient if you want to store cookies in a human-readable file. Changed in version 3.8: The filename parameter supports a path-like object. | python.library.http.cookiejar#http.cookiejar.LWPCookieJar |
class http.cookiejar.MozillaCookieJar(filename, delayload=None, policy=None)
A FileCookieJar that can load from and save cookies to disk in the Mozilla cookies.txt file format (which is also used by the Lynx and Netscape browsers). Note This loses information about RFC 2965 cookies, and also about newer or non-standard cookie-attributes such as port. Warning Back up your cookies before saving if you have cookies whose loss / corruption would be inconvenient (there are some subtleties which may lead to slight changes in the file over a load / save round-trip). Also note that cookies saved while Mozilla is running will get clobbered by Mozilla. | python.library.http.cookiejar#http.cookiejar.MozillaCookieJar |
http.cookies — HTTP state management Source code: Lib/http/cookies.py The http.cookies module defines classes for abstracting the concept of cookies, an HTTP state management mechanism. It supports both simple string-only cookies, and provides an abstraction for having any serializable data-type as cookie value. The module formerly strictly applied the parsing rules described in the RFC 2109 and RFC 2068 specifications. It has since been discovered that MSIE 3.0x doesn’t follow the character rules outlined in those specs and also many current day browsers and servers have relaxed parsing rules when comes to Cookie handling. As a result, the parsing rules used are a bit less strict. The character set, string.ascii_letters, string.digits and !#$%&'*+-.^_`|~: denote the set of valid characters allowed by this module in Cookie name (as key). Changed in version 3.3: Allowed ‘:’ as a valid Cookie name character. Note On encountering an invalid cookie, CookieError is raised, so if your cookie data comes from a browser you should always prepare for invalid data and catch CookieError on parsing.
exception http.cookies.CookieError
Exception failing because of RFC 2109 invalidity: incorrect attributes, incorrect Set-Cookie header, etc.
class http.cookies.BaseCookie([input])
This class is a dictionary-like object whose keys are strings and whose values are Morsel instances. Note that upon setting a key to a value, the value is first converted to a Morsel containing the key and the value. If input is given, it is passed to the load() method.
class http.cookies.SimpleCookie([input])
This class derives from BaseCookie and overrides value_decode() and value_encode(). SimpleCookie supports strings as cookie values. When setting the value, SimpleCookie calls the builtin str() to convert the value to a string. Values received from HTTP are kept as strings.
See also
Module http.cookiejar
HTTP cookie handling for web clients. The http.cookiejar and http.cookies modules do not depend on each other.
RFC 2109 - HTTP State Management Mechanism
This is the state management specification implemented by this module. Cookie Objects
BaseCookie.value_decode(val)
Return a tuple (real_value, coded_value) from a string representation. real_value can be any type. This method does no decoding in BaseCookie — it exists so it can be overridden.
BaseCookie.value_encode(val)
Return a tuple (real_value, coded_value). val can be any type, but coded_value will always be converted to a string. This method does no encoding in BaseCookie — it exists so it can be overridden. In general, it should be the case that value_encode() and value_decode() are inverses on the range of value_decode.
BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n')
Return a string representation suitable to be sent as HTTP headers. attrs and header are sent to each Morsel’s output() method. sep is used to join the headers together, and is by default the combination '\r\n' (CRLF).
BaseCookie.js_output(attrs=None)
Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP headers was sent. The meaning for attrs is the same as in output().
BaseCookie.load(rawdata)
If rawdata is a string, parse it as an HTTP_COOKIE and add the values found there as Morsels. If it is a dictionary, it is equivalent to: for k, v in rawdata.items():
cookie[k] = v
Morsel Objects
class http.cookies.Morsel
Abstract a key/value pair, which has some RFC 2109 attributes. Morsels are dictionary-like objects, whose set of keys is constant — the valid RFC 2109 attributes, which are expires path comment domain max-age secure version httponly samesite The attribute httponly specifies that the cookie is only transferred in HTTP requests, and is not accessible through JavaScript. This is intended to mitigate some forms of cross-site scripting. The attribute samesite specifies that the browser is not allowed to send the cookie along with cross-site requests. This helps to mitigate CSRF attacks. Valid values for this attribute are “Strict” and “Lax”. The keys are case-insensitive and their default value is ''. Changed in version 3.5: __eq__() now takes key and value into account. Changed in version 3.7: Attributes key, value and coded_value are read-only. Use set() for setting them. Changed in version 3.8: Added support for the samesite attribute.
Morsel.value
The value of the cookie.
Morsel.coded_value
The encoded value of the cookie — this is what should be sent.
Morsel.key
The name of the cookie.
Morsel.set(key, value, coded_value)
Set the key, value and coded_value attributes.
Morsel.isReservedKey(K)
Whether K is a member of the set of keys of a Morsel.
Morsel.output(attrs=None, header='Set-Cookie:')
Return a string representation of the Morsel, suitable to be sent as an HTTP header. By default, all the attributes are included, unless attrs is given, in which case it should be a list of attributes to use. header is by default "Set-Cookie:".
Morsel.js_output(attrs=None)
Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP header was sent. The meaning for attrs is the same as in output().
Morsel.OutputString(attrs=None)
Return a string representing the Morsel, without any surrounding HTTP or JavaScript. The meaning for attrs is the same as in output().
Morsel.update(values)
Update the values in the Morsel dictionary with the values in the dictionary values. Raise an error if any of the keys in the values dict is not a valid RFC 2109 attribute. Changed in version 3.5: an error is raised for invalid keys.
Morsel.copy(value)
Return a shallow copy of the Morsel object. Changed in version 3.5: return a Morsel object instead of a dict.
Morsel.setdefault(key, value=None)
Raise an error if key is not a valid RFC 2109 attribute, otherwise behave the same as dict.setdefault().
Example The following example demonstrates how to use the http.cookies module. >>> from http import cookies
>>> C = cookies.SimpleCookie()
>>> C["fig"] = "newton"
>>> C["sugar"] = "wafer"
>>> print(C) # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> print(C.output()) # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
>>> C = cookies.SimpleCookie()
>>> C["rocky"] = "road"
>>> C["rocky"]["path"] = "/cookie"
>>> print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie
>>> print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road
>>> C = cookies.SimpleCookie()
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
>>> print(C)
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
>>> C = cookies.SimpleCookie()
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
>>> print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
>>> C = cookies.SimpleCookie()
>>> C["oreo"] = "doublestuff"
>>> C["oreo"]["path"] = "/"
>>> print(C)
Set-Cookie: oreo=doublestuff; Path=/
>>> C = cookies.SimpleCookie()
>>> C["twix"] = "none for you"
>>> C["twix"].value
'none for you'
>>> C = cookies.SimpleCookie()
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
>>> C["string"] = "seven"
>>> C["number"].value
'7'
>>> C["string"].value
'seven'
>>> print(C)
Set-Cookie: number=7
Set-Cookie: string=seven | python.library.http.cookies |
class http.cookies.BaseCookie([input])
This class is a dictionary-like object whose keys are strings and whose values are Morsel instances. Note that upon setting a key to a value, the value is first converted to a Morsel containing the key and the value. If input is given, it is passed to the load() method. | python.library.http.cookies#http.cookies.BaseCookie |
BaseCookie.js_output(attrs=None)
Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP headers was sent. The meaning for attrs is the same as in output(). | python.library.http.cookies#http.cookies.BaseCookie.js_output |
BaseCookie.load(rawdata)
If rawdata is a string, parse it as an HTTP_COOKIE and add the values found there as Morsels. If it is a dictionary, it is equivalent to: for k, v in rawdata.items():
cookie[k] = v | python.library.http.cookies#http.cookies.BaseCookie.load |
BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n')
Return a string representation suitable to be sent as HTTP headers. attrs and header are sent to each Morsel’s output() method. sep is used to join the headers together, and is by default the combination '\r\n' (CRLF). | python.library.http.cookies#http.cookies.BaseCookie.output |
BaseCookie.value_decode(val)
Return a tuple (real_value, coded_value) from a string representation. real_value can be any type. This method does no decoding in BaseCookie — it exists so it can be overridden. | python.library.http.cookies#http.cookies.BaseCookie.value_decode |
BaseCookie.value_encode(val)
Return a tuple (real_value, coded_value). val can be any type, but coded_value will always be converted to a string. This method does no encoding in BaseCookie — it exists so it can be overridden. In general, it should be the case that value_encode() and value_decode() are inverses on the range of value_decode. | python.library.http.cookies#http.cookies.BaseCookie.value_encode |
exception http.cookies.CookieError
Exception failing because of RFC 2109 invalidity: incorrect attributes, incorrect Set-Cookie header, etc. | python.library.http.cookies#http.cookies.CookieError |
class http.cookies.Morsel
Abstract a key/value pair, which has some RFC 2109 attributes. Morsels are dictionary-like objects, whose set of keys is constant — the valid RFC 2109 attributes, which are expires path comment domain max-age secure version httponly samesite The attribute httponly specifies that the cookie is only transferred in HTTP requests, and is not accessible through JavaScript. This is intended to mitigate some forms of cross-site scripting. The attribute samesite specifies that the browser is not allowed to send the cookie along with cross-site requests. This helps to mitigate CSRF attacks. Valid values for this attribute are “Strict” and “Lax”. The keys are case-insensitive and their default value is ''. Changed in version 3.5: __eq__() now takes key and value into account. Changed in version 3.7: Attributes key, value and coded_value are read-only. Use set() for setting them. Changed in version 3.8: Added support for the samesite attribute. | python.library.http.cookies#http.cookies.Morsel |
Morsel.coded_value
The encoded value of the cookie — this is what should be sent. | python.library.http.cookies#http.cookies.Morsel.coded_value |
Morsel.copy(value)
Return a shallow copy of the Morsel object. Changed in version 3.5: return a Morsel object instead of a dict. | python.library.http.cookies#http.cookies.Morsel.copy |
Morsel.isReservedKey(K)
Whether K is a member of the set of keys of a Morsel. | python.library.http.cookies#http.cookies.Morsel.isReservedKey |
Morsel.js_output(attrs=None)
Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP header was sent. The meaning for attrs is the same as in output(). | python.library.http.cookies#http.cookies.Morsel.js_output |
Morsel.key
The name of the cookie. | python.library.http.cookies#http.cookies.Morsel.key |
Morsel.output(attrs=None, header='Set-Cookie:')
Return a string representation of the Morsel, suitable to be sent as an HTTP header. By default, all the attributes are included, unless attrs is given, in which case it should be a list of attributes to use. header is by default "Set-Cookie:". | python.library.http.cookies#http.cookies.Morsel.output |
Morsel.OutputString(attrs=None)
Return a string representing the Morsel, without any surrounding HTTP or JavaScript. The meaning for attrs is the same as in output(). | python.library.http.cookies#http.cookies.Morsel.OutputString |
Morsel.set(key, value, coded_value)
Set the key, value and coded_value attributes. | python.library.http.cookies#http.cookies.Morsel.set |
Morsel.setdefault(key, value=None)
Raise an error if key is not a valid RFC 2109 attribute, otherwise behave the same as dict.setdefault(). | python.library.http.cookies#http.cookies.Morsel.setdefault |
Morsel.update(values)
Update the values in the Morsel dictionary with the values in the dictionary values. Raise an error if any of the keys in the values dict is not a valid RFC 2109 attribute. Changed in version 3.5: an error is raised for invalid keys. | python.library.http.cookies#http.cookies.Morsel.update |
Morsel.value
The value of the cookie. | python.library.http.cookies#http.cookies.Morsel.value |
class http.cookies.SimpleCookie([input])
This class derives from BaseCookie and overrides value_decode() and value_encode(). SimpleCookie supports strings as cookie values. When setting the value, SimpleCookie calls the builtin str() to convert the value to a string. Values received from HTTP are kept as strings. | python.library.http.cookies#http.cookies.SimpleCookie |
class http.HTTPStatus
New in version 3.5. A subclass of enum.IntEnum that defines a set of HTTP status codes, reason phrases and long descriptions written in English. Usage: >>> from http import HTTPStatus
>>> HTTPStatus.OK
<HTTPStatus.OK: 200>
>>> HTTPStatus.OK == 200
True
>>> HTTPStatus.OK.value
200
>>> HTTPStatus.OK.phrase
'OK'
>>> HTTPStatus.OK.description
'Request fulfilled, document follows'
>>> list(HTTPStatus)
[<HTTPStatus.CONTINUE: 100>, <HTTPStatus.SWITCHING_PROTOCOLS: 101>, ...] | python.library.http#http.HTTPStatus |
http.server — HTTP servers Source code: Lib/http/server.py This module defines classes for implementing HTTP servers (Web servers). Warning http.server is not recommended for production. It only implements basic security checks. One class, HTTPServer, is a socketserver.TCPServer subclass. It creates and listens at the HTTP socket, dispatching the requests to a handler. Code to create and run the server looks like this: def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
class http.server.HTTPServer(server_address, RequestHandlerClass)
This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port. The server is accessible by the handler, typically through the handler’s server instance variable.
class http.server.ThreadingHTTPServer(server_address, RequestHandlerClass)
This class is identical to HTTPServer but uses threads to handle requests by using the ThreadingMixIn. This is useful to handle web browsers pre-opening sockets, on which HTTPServer would wait indefinitely. New in version 3.7.
The HTTPServer and ThreadingHTTPServer must be given a RequestHandlerClass on instantiation, of which this module provides three different variants:
class http.server.BaseHTTPRequestHandler(request, client_address, server)
This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g. GET or POST). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses. The handler will parse the request and the headers, then call a method specific to the request type. The method name is constructed from the request. For example, for the request method SPAM, the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method. BaseHTTPRequestHandler has the following instance variables:
client_address
Contains a tuple of the form (host, port) referring to the client’s address.
server
Contains the server instance.
close_connection
Boolean that should be set before handle_one_request() returns, indicating if another request may be expected, or if the connection should be shut down.
requestline
Contains the string representation of the HTTP request line. The terminating CRLF is stripped. This attribute should be set by handle_one_request(). If no valid request line was processed, it should be set to the empty string.
command
Contains the command (request type). For example, 'GET'.
path
Contains the request path. If query component of the URL is present, then path includes the query. Using the terminology of RFC 3986, path here includes hier-part and the query.
request_version
Contains the version string from the request. For example, 'HTTP/1.0'.
headers
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request. The parse_headers() function from http.client is used to parse the headers and it requires that the HTTP request provide a valid RFC 2822 style header.
rfile
An io.BufferedIOBase input stream, ready to read from the start of the optional input data.
wfile
Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream in order to achieve successful interoperation with HTTP clients. Changed in version 3.6: This is an io.BufferedIOBase stream.
BaseHTTPRequestHandler has the following attributes:
server_version
Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, 'BaseHTTP/0.2'.
sys_version
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, 'Python/1.4'.
error_message_format
Specifies a format string that should be used by send_error() method for building an error response to the client. The string is filled by default with variables from responses based on the status code that passed to send_error().
error_content_type
Specifies the Content-Type HTTP header of error responses sent to the client. The default value is 'text/html'.
protocol_version
This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'.
MessageClass
Specifies an email.message.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to http.client.HTTPMessage.
responses
This attribute contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage,
longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key. It is used by send_response_only() and send_error() methods.
A BaseHTTPRequestHandler instance has the following methods:
handle()
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.
handle_one_request()
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.
handle_expect_100()
When a HTTP/1.1 compliant server receives an Expect: 100-continue request header it responds back with a 100 Continue followed by 200
OK headers. This method can be overridden to raise an error if the server does not want the client to continue. For e.g. server can chose to send 417
Expectation Failed as a response header and return False. New in version 3.2.
send_error(code, message=None, explain=None)
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as an optional, short, human readable description of the error. The explain argument can be used to provide more detailed information about the error; it will be formatted using the error_message_format attribute and emitted, after a complete set of headers, as the response body. The responses attribute holds the default values for message and explain that will be used if no value is provided; for unknown codes the default value for both is the string ???. The body will be empty if the method is HEAD or the response code is one of the following: 1xx, 204 No Content, 205 Reset Content, 304 Not Modified. Changed in version 3.4: The error response includes a Content-Length header. Added the explain argument.
send_response(code, message=None)
Adds a response header to the headers buffer and logs the accepted request. The HTTP response line is written to the internal buffer, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively. If the server does not intend to send any other headers using the send_header() method, then send_response() should be followed by an end_headers() call. Changed in version 3.3: Headers are stored to an internal buffer and end_headers() needs to be called explicitly.
send_header(keyword, value)
Adds the HTTP header to an internal buffer which will be written to the output stream when either end_headers() or flush_headers() is invoked. keyword should specify the header keyword, with value specifying its value. Note that, after the send_header calls are done, end_headers() MUST BE called in order to complete the operation. Changed in version 3.2: Headers are stored in an internal buffer.
send_response_only(code, message=None)
Sends the response header only, used for the purposes when 100
Continue response is sent by the server to the client. The headers not buffered and sent directly the output stream.If the message is not specified, the HTTP message corresponding the response code is sent. New in version 3.2.
end_headers()
Adds a blank line (indicating the end of the HTTP headers in the response) to the headers buffer and calls flush_headers(). Changed in version 3.2: The buffered headers are written to the output stream.
flush_headers()
Finally send the headers to the output stream and flush the internal headers buffer. New in version 3.3.
log_request(code='-', size='-')
Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter.
log_error(...)
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values).
log_message(format, ...)
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client ip address and current date and time are prefixed to every message logged.
version_string()
Returns the server software’s version string. This is a combination of the server_version and sys_version attributes.
date_time_string(timestamp=None)
Returns the date and time given by timestamp (which must be None or in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time. The result looks like 'Sun, 06 Nov 1994 08:49:37 GMT'.
log_date_time_string()
Returns the current date and time, formatted for logging.
address_string()
Returns the client address. Changed in version 3.3: Previously, a name lookup was performed. To avoid name resolution delays, it now always returns the IP address.
class http.server.SimpleHTTPRequestHandler(request, client_address, server, directory=None)
This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests. A lot of the work, such as parsing the request, is done by the base class BaseHTTPRequestHandler. This class implements the do_GET() and do_HEAD() functions. The following are defined as class-level attributes of SimpleHTTPRequestHandler:
server_version
This will be "SimpleHTTP/" + __version__, where __version__ is defined at the module level.
extensions_map
A dictionary mapping suffixes into MIME types, contains custom overrides for the default system mappings. The mapping is used case-insensitively, and so should contain only lower-cased keys. Changed in version 3.9: This dictionary is no longer filled with the default system mappings, but only contains overrides.
directory
If not specified, the directory to serve is the current working directory. Changed in version 3.9: Accepts a path-like object.
The SimpleHTTPRequestHandler class defines the following methods:
do_HEAD()
This method serves the 'HEAD' request type: it sends the headers it would send for the equivalent GET request. See the do_GET() method for a more complete explanation of the possible headers.
do_GET()
The request is mapped to a local file by interpreting the request as a path relative to the current working directory. If the request was mapped to a directory, the directory is checked for a file named index.html or index.htm (in that order). If found, the file’s contents are returned; otherwise a directory listing is generated by calling the list_directory() method. This method uses os.listdir() to scan the directory, and returns a 404 error response if the listdir() fails. If the request was mapped to a file, it is opened. Any OSError exception in opening the requested file is mapped to a 404, 'File not found' error. If there was a 'If-Modified-Since' header in the request, and the file was not modified after this time, a 304, 'Not Modified' response is sent. Otherwise, the content type is guessed by calling the guess_type() method, which in turn uses the extensions_map variable, and the file contents are returned. A 'Content-type:' header with the guessed content type is output, followed by a 'Content-Length:' header with the file’s size and a 'Last-Modified:' header with the file’s modification time. Then follows a blank line signifying the end of the headers, and then the contents of the file are output. If the file’s MIME type starts with text/ the file is opened in text mode; otherwise binary mode is used. For example usage, see the implementation of the test() function invocation in the http.server module. Changed in version 3.7: Support of the 'If-Modified-Since' header.
The SimpleHTTPRequestHandler class can be used in the following manner in order to create a very basic webserver serving files relative to the current directory: import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
http.server can also be invoked directly using the -m switch of the interpreter with a port number argument. Similar to the previous example, this serves files relative to the current directory: python -m http.server 8000
By default, server binds itself to all interfaces. The option -b/--bind specifies a specific address to which it should bind. Both IPv4 and IPv6 addresses are supported. For example, the following command causes the server to bind to localhost only: python -m http.server 8000 --bind 127.0.0.1
New in version 3.4: --bind argument was introduced. New in version 3.8: --bind argument enhanced to support IPv6 By default, server uses the current directory. The option -d/--directory specifies a directory to which it should serve the files. For example, the following command uses a specific directory: python -m http.server --directory /tmp/
New in version 3.7: --directory specify alternate directory
class http.server.CGIHTTPRequestHandler(request, client_address, server)
This class is used to serve either files or output of CGI scripts from the current directory and below. Note that mapping HTTP hierarchic structure to local directory structure is exactly as in SimpleHTTPRequestHandler. Note CGI scripts run by the CGIHTTPRequestHandler class cannot execute redirects (HTTP code 302), because code 200 (script output follows) is sent prior to execution of the CGI script. This pre-empts the status code. The class will however, run the CGI script, instead of serving it as a file, if it guesses it to be a CGI script. Only directory-based CGI are used — the other common server configuration is to treat special extensions as denoting CGI scripts. The do_GET() and do_HEAD() functions are modified to run CGI scripts and serve the output, instead of serving files, if the request leads to somewhere below the cgi_directories path. The CGIHTTPRequestHandler defines the following data member:
cgi_directories
This defaults to ['/cgi-bin', '/htbin'] and describes directories to treat as containing CGI scripts.
The CGIHTTPRequestHandler defines the following method:
do_POST()
This method serves the 'POST' request type, only allowed for CGI scripts. Error 501, “Can only POST to CGI scripts”, is output when trying to POST to a non-CGI url.
Note that CGI scripts will be run with UID of user nobody, for security reasons. Problems with the CGI script will be translated to error 403.
CGIHTTPRequestHandler can be enabled in the command line by passing the --cgi option: python -m http.server --cgi 8000 | python.library.http.server |
class http.server.BaseHTTPRequestHandler(request, client_address, server)
This class is used to handle the HTTP requests that arrive at the server. By itself, it cannot respond to any actual HTTP requests; it must be subclassed to handle each request method (e.g. GET or POST). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses. The handler will parse the request and the headers, then call a method specific to the request type. The method name is constructed from the request. For example, for the request method SPAM, the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method. BaseHTTPRequestHandler has the following instance variables:
client_address
Contains a tuple of the form (host, port) referring to the client’s address.
server
Contains the server instance.
close_connection
Boolean that should be set before handle_one_request() returns, indicating if another request may be expected, or if the connection should be shut down.
requestline
Contains the string representation of the HTTP request line. The terminating CRLF is stripped. This attribute should be set by handle_one_request(). If no valid request line was processed, it should be set to the empty string.
command
Contains the command (request type). For example, 'GET'.
path
Contains the request path. If query component of the URL is present, then path includes the query. Using the terminology of RFC 3986, path here includes hier-part and the query.
request_version
Contains the version string from the request. For example, 'HTTP/1.0'.
headers
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request. The parse_headers() function from http.client is used to parse the headers and it requires that the HTTP request provide a valid RFC 2822 style header.
rfile
An io.BufferedIOBase input stream, ready to read from the start of the optional input data.
wfile
Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream in order to achieve successful interoperation with HTTP clients. Changed in version 3.6: This is an io.BufferedIOBase stream.
BaseHTTPRequestHandler has the following attributes:
server_version
Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, 'BaseHTTP/0.2'.
sys_version
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, 'Python/1.4'.
error_message_format
Specifies a format string that should be used by send_error() method for building an error response to the client. The string is filled by default with variables from responses based on the status code that passed to send_error().
error_content_type
Specifies the Content-Type HTTP header of error responses sent to the client. The default value is 'text/html'.
protocol_version
This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'.
MessageClass
Specifies an email.message.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to http.client.HTTPMessage.
responses
This attribute contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage,
longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key. It is used by send_response_only() and send_error() methods.
A BaseHTTPRequestHandler instance has the following methods:
handle()
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.
handle_one_request()
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.
handle_expect_100()
When a HTTP/1.1 compliant server receives an Expect: 100-continue request header it responds back with a 100 Continue followed by 200
OK headers. This method can be overridden to raise an error if the server does not want the client to continue. For e.g. server can chose to send 417
Expectation Failed as a response header and return False. New in version 3.2.
send_error(code, message=None, explain=None)
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as an optional, short, human readable description of the error. The explain argument can be used to provide more detailed information about the error; it will be formatted using the error_message_format attribute and emitted, after a complete set of headers, as the response body. The responses attribute holds the default values for message and explain that will be used if no value is provided; for unknown codes the default value for both is the string ???. The body will be empty if the method is HEAD or the response code is one of the following: 1xx, 204 No Content, 205 Reset Content, 304 Not Modified. Changed in version 3.4: The error response includes a Content-Length header. Added the explain argument.
send_response(code, message=None)
Adds a response header to the headers buffer and logs the accepted request. The HTTP response line is written to the internal buffer, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively. If the server does not intend to send any other headers using the send_header() method, then send_response() should be followed by an end_headers() call. Changed in version 3.3: Headers are stored to an internal buffer and end_headers() needs to be called explicitly.
send_header(keyword, value)
Adds the HTTP header to an internal buffer which will be written to the output stream when either end_headers() or flush_headers() is invoked. keyword should specify the header keyword, with value specifying its value. Note that, after the send_header calls are done, end_headers() MUST BE called in order to complete the operation. Changed in version 3.2: Headers are stored in an internal buffer.
send_response_only(code, message=None)
Sends the response header only, used for the purposes when 100
Continue response is sent by the server to the client. The headers not buffered and sent directly the output stream.If the message is not specified, the HTTP message corresponding the response code is sent. New in version 3.2.
end_headers()
Adds a blank line (indicating the end of the HTTP headers in the response) to the headers buffer and calls flush_headers(). Changed in version 3.2: The buffered headers are written to the output stream.
flush_headers()
Finally send the headers to the output stream and flush the internal headers buffer. New in version 3.3.
log_request(code='-', size='-')
Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter.
log_error(...)
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values).
log_message(format, ...)
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client ip address and current date and time are prefixed to every message logged.
version_string()
Returns the server software’s version string. This is a combination of the server_version and sys_version attributes.
date_time_string(timestamp=None)
Returns the date and time given by timestamp (which must be None or in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time. The result looks like 'Sun, 06 Nov 1994 08:49:37 GMT'.
log_date_time_string()
Returns the current date and time, formatted for logging.
address_string()
Returns the client address. Changed in version 3.3: Previously, a name lookup was performed. To avoid name resolution delays, it now always returns the IP address. | python.library.http.server#http.server.BaseHTTPRequestHandler |
address_string()
Returns the client address. Changed in version 3.3: Previously, a name lookup was performed. To avoid name resolution delays, it now always returns the IP address. | python.library.http.server#http.server.BaseHTTPRequestHandler.address_string |
client_address
Contains a tuple of the form (host, port) referring to the client’s address. | python.library.http.server#http.server.BaseHTTPRequestHandler.client_address |
close_connection
Boolean that should be set before handle_one_request() returns, indicating if another request may be expected, or if the connection should be shut down. | python.library.http.server#http.server.BaseHTTPRequestHandler.close_connection |
command
Contains the command (request type). For example, 'GET'. | python.library.http.server#http.server.BaseHTTPRequestHandler.command |
date_time_string(timestamp=None)
Returns the date and time given by timestamp (which must be None or in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time. The result looks like 'Sun, 06 Nov 1994 08:49:37 GMT'. | python.library.http.server#http.server.BaseHTTPRequestHandler.date_time_string |
end_headers()
Adds a blank line (indicating the end of the HTTP headers in the response) to the headers buffer and calls flush_headers(). Changed in version 3.2: The buffered headers are written to the output stream. | python.library.http.server#http.server.BaseHTTPRequestHandler.end_headers |
error_content_type
Specifies the Content-Type HTTP header of error responses sent to the client. The default value is 'text/html'. | python.library.http.server#http.server.BaseHTTPRequestHandler.error_content_type |
error_message_format
Specifies a format string that should be used by send_error() method for building an error response to the client. The string is filled by default with variables from responses based on the status code that passed to send_error(). | python.library.http.server#http.server.BaseHTTPRequestHandler.error_message_format |
flush_headers()
Finally send the headers to the output stream and flush the internal headers buffer. New in version 3.3. | python.library.http.server#http.server.BaseHTTPRequestHandler.flush_headers |
handle()
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods. | python.library.http.server#http.server.BaseHTTPRequestHandler.handle |
handle_expect_100()
When a HTTP/1.1 compliant server receives an Expect: 100-continue request header it responds back with a 100 Continue followed by 200
OK headers. This method can be overridden to raise an error if the server does not want the client to continue. For e.g. server can chose to send 417
Expectation Failed as a response header and return False. New in version 3.2. | python.library.http.server#http.server.BaseHTTPRequestHandler.handle_expect_100 |
handle_one_request()
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it. | python.library.http.server#http.server.BaseHTTPRequestHandler.handle_one_request |
headers
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request. The parse_headers() function from http.client is used to parse the headers and it requires that the HTTP request provide a valid RFC 2822 style header. | python.library.http.server#http.server.BaseHTTPRequestHandler.headers |
log_date_time_string()
Returns the current date and time, formatted for logging. | python.library.http.server#http.server.BaseHTTPRequestHandler.log_date_time_string |
log_error(...)
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values). | python.library.http.server#http.server.BaseHTTPRequestHandler.log_error |
log_message(format, ...)
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client ip address and current date and time are prefixed to every message logged. | python.library.http.server#http.server.BaseHTTPRequestHandler.log_message |
log_request(code='-', size='-')
Logs an accepted (successful) request. code should specify the numeric HTTP code associated with the response. If a size of the response is available, then it should be passed as the size parameter. | python.library.http.server#http.server.BaseHTTPRequestHandler.log_request |
MessageClass
Specifies an email.message.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to http.client.HTTPMessage. | python.library.http.server#http.server.BaseHTTPRequestHandler.MessageClass |
path
Contains the request path. If query component of the URL is present, then path includes the query. Using the terminology of RFC 3986, path here includes hier-part and the query. | python.library.http.server#http.server.BaseHTTPRequestHandler.path |
protocol_version
This specifies the HTTP protocol version used in responses. If set to 'HTTP/1.1', the server will permit HTTP persistent connections; however, your server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to 'HTTP/1.0'. | python.library.http.server#http.server.BaseHTTPRequestHandler.protocol_version |
requestline
Contains the string representation of the HTTP request line. The terminating CRLF is stripped. This attribute should be set by handle_one_request(). If no valid request line was processed, it should be set to the empty string. | python.library.http.server#http.server.BaseHTTPRequestHandler.requestline |
request_version
Contains the version string from the request. For example, 'HTTP/1.0'. | python.library.http.server#http.server.BaseHTTPRequestHandler.request_version |
responses
This attribute contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage,
longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key. It is used by send_response_only() and send_error() methods. | python.library.http.server#http.server.BaseHTTPRequestHandler.responses |
rfile
An io.BufferedIOBase input stream, ready to read from the start of the optional input data. | python.library.http.server#http.server.BaseHTTPRequestHandler.rfile |
send_error(code, message=None, explain=None)
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as an optional, short, human readable description of the error. The explain argument can be used to provide more detailed information about the error; it will be formatted using the error_message_format attribute and emitted, after a complete set of headers, as the response body. The responses attribute holds the default values for message and explain that will be used if no value is provided; for unknown codes the default value for both is the string ???. The body will be empty if the method is HEAD or the response code is one of the following: 1xx, 204 No Content, 205 Reset Content, 304 Not Modified. Changed in version 3.4: The error response includes a Content-Length header. Added the explain argument. | python.library.http.server#http.server.BaseHTTPRequestHandler.send_error |
send_header(keyword, value)
Adds the HTTP header to an internal buffer which will be written to the output stream when either end_headers() or flush_headers() is invoked. keyword should specify the header keyword, with value specifying its value. Note that, after the send_header calls are done, end_headers() MUST BE called in order to complete the operation. Changed in version 3.2: Headers are stored in an internal buffer. | python.library.http.server#http.server.BaseHTTPRequestHandler.send_header |
send_response(code, message=None)
Adds a response header to the headers buffer and logs the accepted request. The HTTP response line is written to the internal buffer, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively. If the server does not intend to send any other headers using the send_header() method, then send_response() should be followed by an end_headers() call. Changed in version 3.3: Headers are stored to an internal buffer and end_headers() needs to be called explicitly. | python.library.http.server#http.server.BaseHTTPRequestHandler.send_response |
send_response_only(code, message=None)
Sends the response header only, used for the purposes when 100
Continue response is sent by the server to the client. The headers not buffered and sent directly the output stream.If the message is not specified, the HTTP message corresponding the response code is sent. New in version 3.2. | python.library.http.server#http.server.BaseHTTPRequestHandler.send_response_only |
server
Contains the server instance. | python.library.http.server#http.server.BaseHTTPRequestHandler.server |
server_version
Specifies the server software version. You may want to override this. The format is multiple whitespace-separated strings, where each string is of the form name[/version]. For example, 'BaseHTTP/0.2'. | python.library.http.server#http.server.BaseHTTPRequestHandler.server_version |
sys_version
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, 'Python/1.4'. | python.library.http.server#http.server.BaseHTTPRequestHandler.sys_version |
version_string()
Returns the server software’s version string. This is a combination of the server_version and sys_version attributes. | python.library.http.server#http.server.BaseHTTPRequestHandler.version_string |
wfile
Contains the output stream for writing a response back to the client. Proper adherence to the HTTP protocol must be used when writing to this stream in order to achieve successful interoperation with HTTP clients. Changed in version 3.6: This is an io.BufferedIOBase stream. | python.library.http.server#http.server.BaseHTTPRequestHandler.wfile |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.