Index: Misc/cheatsheet =================================================================== --- Misc/cheatsheet (revisão 62992) +++ Misc/cheatsheet (cópia de trabalho) @@ -1801,7 +1801,6 @@ asyncore Asynchronous File I/O (in select style) atexit Register functions to be called at exit of Python interpreter. base64 Conversions to/from base64 RFC-MIME transport encoding . -BaseHTTPServer Base class forhttp services. Bastion "Bastionification" utility (control access to instance vars) bdb A generic Python debugger base class. binhex Macintosh binhex compression/decompression. @@ -1810,7 +1809,6 @@ calendar Calendar printing functions. cgi Wraps the WWW Forms Common Gateway Interface (CGI). cgitb Utility for handling CGI tracebacks. -CGIHTTPServer CGI http services. cmd A generic class to build line-oriented command interpreters. datetime Basic date and time types. code Utilities needed to emulate Python's interactive interpreter @@ -1854,7 +1852,8 @@ htmlentitydefs Proposed entity definitions for HTML. htmllib HTML parsing utilities. HTMLParser A parser for HTML and XHTML. -httplib HTTP client class. +http.client HTTP client class. +http.server Package for http services (base class, CGI and simple http server) ihooks Hooks into the "import" mechanism. imaplib IMAP4 client.Based on RFC 2060. imghdr Recognizing image files based on their first few bytes. @@ -1914,7 +1913,6 @@ shelve Manage shelves of pickled objects. shlex Lexical analyzer class for simple shell-like syntaxes. shutil Utility functions usable in a shell-like program. -SimpleHTTPServer Simple extension to base http class site Append module search paths for third-party packages to sys.path. smtplib SMTP Client class (RFC 821) Index: Doc/howto/urllib2.rst =================================================================== --- Doc/howto/urllib2.rst (revisão 62992) +++ Doc/howto/urllib2.rst (cópia de trabalho) @@ -230,7 +230,7 @@ codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range. -``BaseHTTPServer.BaseHTTPRequestHandler.responses`` is a useful dictionary of +``http.server.BaseHTTPRequestHandler.responses`` is a useful dictionary of response codes in that shows all the response codes used by RFC 2616. The dictionary is reproduced here for convenience :: @@ -385,7 +385,7 @@ **info** - this returns a dictionary-like object that describes the page fetched, particularly the headers sent by the server. It is currently an -``httplib.HTTPMessage`` instance. +``http.client.HTTPMessage`` instance. Typical headers include 'Content-length', 'Content-type', and so on. See the `Quick Reference to HTTP Headers `_ @@ -526,12 +526,12 @@ ================== The Python support for fetching resources from the web is layered. urllib2 uses -the httplib library, which in turn uses the socket library. +the http.client library, which in turn uses the socket library. As of Python 2.3 you can specify how long a socket should wait for a response before timing out. This can be useful in applications which have to fetch web pages. By default the socket module has *no timeout* and can hang. Currently, -the socket timeout is not exposed at the httplib or urllib2 levels. However, +the socket timeout is not exposed at the http.client or urllib2 levels. However, you can set the default timeout globally for all sockets using :: import socket Index: Doc/library/cookie.rst =================================================================== --- Doc/library/cookie.rst (revisão 62992) +++ Doc/library/cookie.rst (cópia de trabalho) @@ -1,281 +0,0 @@ - -:mod:`Cookie` --- HTTP state management -======================================= - -.. module:: Cookie - :synopsis: Support for HTTP state management (cookies). -.. moduleauthor:: Timothy O'Malley -.. sectionauthor:: Moshe Zadka - - -The :mod:`Cookie` 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. As a -result, the parsing rules used are a bit less strict. - - -.. exception:: CookieError - - Exception failing because of :rfc:`2109` invalidity: incorrect attributes, - incorrect :mailheader:`Set-Cookie` header, etc. - - -.. class:: BaseCookie([input]) - - This class is a dictionary-like object whose keys are strings and whose values - are :class:`Morsel` instances. Note that upon setting a key to a value, the - value is first converted to a :class:`Morsel` containing the key and the value. - - If *input* is given, it is passed to the :meth:`load` method. - - -.. class:: SimpleCookie([input]) - - This class derives from :class:`BaseCookie` and overrides :meth:`value_decode` - and :meth:`value_encode` to be the identity and :func:`str` respectively. - - -.. class:: SerialCookie([input]) - - This class derives from :class:`BaseCookie` and overrides :meth:`value_decode` - and :meth:`value_encode` to be the :func:`pickle.loads` and - :func:`pickle.dumps`. - - .. deprecated:: 2.3 - Reading pickled values from untrusted cookie data is a huge security hole, as - pickle strings can be crafted to cause arbitrary code to execute on your server. - It is supported for backwards compatibility only, and may eventually go away. - - -.. class:: SmartCookie([input]) - - This class derives from :class:`BaseCookie`. It overrides :meth:`value_decode` - to be :func:`pickle.loads` if it is a valid pickle, and otherwise the value - itself. It overrides :meth:`value_encode` to be :func:`pickle.dumps` unless it - is a string, in which case it returns the value itself. - - .. deprecated:: 2.3 - The same security warning from :class:`SerialCookie` applies here. - -A further security note is warranted. For backwards compatibility, the -:mod:`Cookie` module exports a class named :class:`Cookie` which is just an -alias for :class:`SmartCookie`. This is probably a mistake and will likely be -removed in a future version. You should not use the :class:`Cookie` class in -your applications, for the same reason why you should not use the -:class:`SerialCookie` class. - - -.. seealso:: - - Module :mod:`cookielib` - HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie` - 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: - -Cookie Objects --------------- - - -.. method:: BaseCookie.value_decode(val) - - Return a decoded value from a string representation. Return value can be any - type. This method does nothing in :class:`BaseCookie` --- it exists so it can be - overridden. - - -.. method:: BaseCookie.value_encode(val) - - Return an encoded value. *val* can be any type, but return value must be a - string. This method does nothing in :class:`BaseCookie` --- it exists so it can - be overridden - - In general, it should be the case that :meth:`value_encode` and - :meth:`value_decode` are inverses on the range of *value_decode*. - - -.. method:: BaseCookie.output([attrs[, header[, sep]]]) - - Return a string representation suitable to be sent as HTTP headers. *attrs* and - *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used - to join the headers together, and is by default the combination ``'\r\n'`` - (CRLF). - - -.. method:: BaseCookie.js_output([attrs]) - - 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 :meth:`output`. - - -.. method:: BaseCookie.load(rawdata) - - If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values - found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to:: - - for k, v in rawdata.items(): - cookie[k] = v - - -.. _morsel-objects: - -Morsel Objects --------------- - - -.. class:: 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`` - - The keys are case-insensitive. - - -.. attribute:: Morsel.value - - The value of the cookie. - - -.. attribute:: Morsel.coded_value - - The encoded value of the cookie --- this is what should be sent. - - -.. attribute:: Morsel.key - - The name of the cookie. - - -.. method:: Morsel.set(key, value, coded_value) - - Set the *key*, *value* and *coded_value* members. - - -.. method:: Morsel.isReservedKey(K) - - Whether *K* is a member of the set of keys of a :class:`Morsel`. - - -.. method:: Morsel.output([attrs[, header]]) - - 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:"``. - - -.. method:: Morsel.js_output([attrs]) - - 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 :meth:`output`. - - -.. method:: Morsel.OutputString([attrs]) - - Return a string representing the Morsel, without any surrounding HTTP or - JavaScript. - - The meaning for *attrs* is the same as in :meth:`output`. - - -.. _cookie-example: - -Example -------- - -The following example demonstrates how to use the :mod:`Cookie` module. - -.. doctest:: - :options: +NORMALIZE_WHITESPACE - - >>> import Cookie - >>> C = Cookie.SimpleCookie() - >>> C = Cookie.SerialCookie() - >>> C = Cookie.SmartCookie() - >>> 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 = Cookie.SmartCookie() - >>> 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 = Cookie.SmartCookie() - >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) - >>> print(C) - Set-Cookie: chips=ahoy - Set-Cookie: vienna=finger - >>> C = Cookie.SmartCookie() - >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') - >>> print(C) - Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" - >>> C = Cookie.SmartCookie() - >>> C["oreo"] = "doublestuff" - >>> C["oreo"]["path"] = "/" - >>> print(C) - Set-Cookie: oreo=doublestuff; Path=/ - >>> C = Cookie.SmartCookie() - >>> C["twix"] = "none for you" - >>> C["twix"].value - 'none for you' - >>> C = Cookie.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 - >>> C = Cookie.SerialCookie() - >>> C["number"] = 7 - >>> C["string"] = "seven" - >>> C["number"].value - 7 - >>> C["string"].value - 'seven' - >>> print(C) - Set-Cookie: number="I7\012." - Set-Cookie: string="S'seven'\012p1\012." - >>> C = Cookie.SmartCookie() - >>> C["number"] = 7 - >>> C["string"] = "seven" - >>> C["number"].value - 7 - >>> C["string"].value - 'seven' - >>> print(C) - Set-Cookie: number="I7\012." - Set-Cookie: string=seven - Index: Doc/library/simplehttpserver.rst =================================================================== --- Doc/library/simplehttpserver.rst (revisão 62992) +++ Doc/library/simplehttpserver.rst (cópia de trabalho) @@ -1,86 +0,0 @@ - -:mod:`SimpleHTTPServer` --- Simple HTTP request handler -======================================================= - -.. module:: SimpleHTTPServer - :synopsis: This module provides a basic request handler for HTTP servers. -.. sectionauthor:: Moshe Zadka - - -The :mod:`SimpleHTTPServer` module defines a single class, -:class:`SimpleHTTPRequestHandler`, which is interface-compatible with -:class:`BaseHTTPServer.BaseHTTPRequestHandler`. - -The :mod:`SimpleHTTPServer` module defines the following class: - - -.. class:: SimpleHTTPRequestHandler(request, client_address, server) - - 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 - :class:`BaseHTTPServer.BaseHTTPRequestHandler`. This class implements the - :func:`do_GET` and :func:`do_HEAD` functions. - - The following are defined as class-level attributes of - :class:`SimpleHTTPRequestHandler`: - - - .. attribute:: server_version - - This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is - defined at the module level. - - - .. attribute:: extensions_map - - A dictionary mapping suffixes into MIME types. The default is - signified by an empty string, and is considered to be - ``application/octet-stream``. The mapping is used case-insensitively, - and so should contain only lower-cased keys. - - The :class:`SimpleHTTPRequestHandler` class defines the following methods: - - - .. method:: do_HEAD() - - This method serves the ``'HEAD'`` request type: it sends the headers it - would send for the equivalent ``GET`` request. See the :meth:`do_GET` - method for a more complete explanation of the possible headers. - - - .. method:: 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 :meth:`list_directory` method. This method uses - :func:`os.listdir` to scan the directory, and returns a ``404`` error - response if the :func:`listdir` fails. - - If the request was mapped to a file, it is opened and the contents are - returned. Any :exc:`IOError` exception in opening the requested file is - mapped to a ``404``, ``'File not found'`` error. Otherwise, the content - type is guessed by calling the :meth:`guess_type` method, which in turn - uses the *extensions_map* variable. - - 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 :func:`test` function. - - -.. seealso:: - - Module :mod:`BaseHTTPServer` - Base class implementation for Web server and request handler. - Index: Doc/library/urllib2.rst =================================================================== --- Doc/library/urllib2.rst (revisão 62992) +++ Doc/library/urllib2.rst (cópia de trabalho) @@ -37,7 +37,7 @@ determine if a redirect was followed * :meth:`info` --- return the meta-information of the page, such as headers, in - the form of an ``httplib.HTTPMessage`` instance + the form of an ``http.client.HTTPMessage`` instance (see `Quick Reference to HTTP Headers `_) Raises :exc:`URLError` on errors. @@ -101,7 +101,7 @@ An HTTP status code as defined in `RFC 2616 `_. This numeric value corresponds to a value found in the dictionary of - codes as found in :attr:`BaseHTTPServer.BaseHTTPRequestHandler.responses`. + codes as found in :attr:`http.server.BaseHTTPRequestHandler.responses`. @@ -134,7 +134,7 @@ HTTP cookies: *origin_req_host* should be the request-host of the origin transaction, as - defined by :rfc:`2965`. It defaults to ``cookielib.request_host(self)``. This + defined by :rfc:`2965`. It defaults to ``http.cookiejar.request_host(self)``. This is the host name or IP address of the original request that was initiated by the user. For example, if the request is for an image in an HTML document, this should be the request-host of the request for the page containing the image. @@ -627,7 +627,7 @@ .. attribute:: HTTPCookieProcessor.cookiejar - The :class:`cookielib.CookieJar` in which cookies are stored. + The :class:`http.cookiejar.CookieJar` in which cookies are stored. .. _proxy-handler: Index: Doc/library/cookielib.rst =================================================================== --- Doc/library/cookielib.rst (revisão 62992) +++ Doc/library/cookielib.rst (cópia de trabalho) @@ -1,760 +0,0 @@ - -:mod:`cookielib` --- Cookie handling for HTTP clients -===================================================== - -.. module:: cookielib - :synopsis: Classes for automatic handling of HTTP cookies. -.. moduleauthor:: John J. Lee -.. sectionauthor:: John J. Lee - - -The :mod:`cookielib` module defines classes for automatic handling of HTTP -cookies. It is useful for accessing web sites that require small pieces of data --- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a -web server, and then returned to the server in later HTTP requests. - -Both the regular Netscape cookie protocol and the protocol defined by -:rfc:`2965` are handled. RFC 2965 handling is switched off by default. -:rfc:`2109` cookies are parsed as Netscape cookies and subsequently treated -either as Netscape or RFC 2965 cookies according to the 'policy' in effect. -Note that the great majority of cookies on the Internet are Netscape cookies. -:mod:`cookielib` attempts to follow the de-facto Netscape cookie protocol (which -differs substantially from that set out in the original Netscape specification), -including taking note of the ``max-age`` and ``port`` cookie-attributes -introduced with RFC 2965. - -.. note:: - - The various named parameters found in :mailheader:`Set-Cookie` and - :mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are - conventionally referred to as :dfn:`attributes`. To distinguish them from - Python attributes, the documentation for this module uses the term - :dfn:`cookie-attribute` instead. - - -The module defines the following exception: - - -.. exception:: LoadError - - Instances of :class:`FileCookieJar` raise this exception on failure to load - cookies from a file. - - .. note:: - - For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`), - :exc:`LoadError` is a subclass of :exc:`IOError`. - - -The following classes are provided: - - -.. class:: CookieJar(policy=None) - - *policy* is an object implementing the :class:`CookiePolicy` interface. - - The :class:`CookieJar` class stores HTTP cookies. It extracts cookies from HTTP - requests, and returns them in HTTP responses. :class:`CookieJar` instances - automatically expire contained cookies when necessary. Subclasses are also - responsible for storing and retrieving cookies from a file or database. - - -.. class:: FileCookieJar(filename, delayload=None, policy=None) - - *policy* is an object implementing the :class:`CookiePolicy` interface. For the - other arguments, see the documentation for the corresponding attributes. - - A :class:`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 - :meth:`load` or :meth:`revert` method is called. Subclasses of this class are - documented in section :ref:`file-cookie-jar-classes`. - - -.. class:: CookiePolicy() - - This class is responsible for deciding whether each cookie should be accepted - from / returned to the server. - - -.. class:: 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 ) - - 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 :const:`None`, this is a - sequence of the only domains for which we accept and return cookies. For all - other arguments, see the documentation for :class:`CookiePolicy` and - :class:`DefaultCookiePolicy` objects. - - :class:`DefaultCookiePolicy` implements the standard accept / reject rules for - Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (ie. cookies - received in a :mailheader:`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 :attr:`rfc2109_as_netscape` is True, RFC 2109 cookies are - 'downgraded' by the :class:`CookieJar` instance to Netscape cookies, by - setting the :attr:`version` attribute of the :class:`Cookie` instance to 0. - :class:`DefaultCookiePolicy` also provides some parameters to allow some - fine-tuning of policy. - - -.. class:: Cookie() - - This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not - expected that users of :mod:`cookielib` construct their own :class:`Cookie` - instances. Instead, if necessary, call :meth:`make_cookies` on a - :class:`CookieJar` instance. - - -.. seealso:: - - Module :mod:`urllib2` - URL opening with automatic cookie handling. - - Module :mod:`Cookie` - HTTP cookie classes, principally useful for server-side code. The - :mod:`cookielib` and :mod:`Cookie` modules do not depend on each other. - - http://wwwsearch.sf.net/ClientCookie/ - Extensions to this module, including a class for reading Microsoft Internet - Explorer cookies on Windows. - - http://wp.netscape.com/newsref/std/cookie_spec.html - The specification of the original Netscape cookie protocol. Though this is - still the dominant protocol, the 'Netscape cookie protocol' implemented by all - the major browsers (and :mod:`cookielib`) only bears a passing resemblance to - the one sketched out in ``cookie_spec.html``. - - :rfc:`2109` - HTTP State Management Mechanism - Obsoleted by RFC 2965. Uses :mailheader:`Set-Cookie` with version=1. - - :rfc:`2965` - HTTP State Management Mechanism - The Netscape protocol with the bugs fixed. Uses :mailheader:`Set-Cookie2` in - place of :mailheader:`Set-Cookie`. Not widely used. - - http://kristol.org/cookie/errata.html - Unfinished errata to RFC 2965. - - :rfc:`2964` - Use of HTTP State Management - -.. _cookie-jar-objects: - -CookieJar and FileCookieJar Objects ------------------------------------ - -:class:`CookieJar` objects support the :term:`iterator` protocol for iterating over -contained :class:`Cookie` objects. - -:class:`CookieJar` has the following methods: - - -.. method:: CookieJar.add_cookie_header(request) - - Add correct :mailheader:`Cookie` header to *request*. - - If policy allows (ie. the :attr:`rfc2965` and :attr:`hide_cookie2` attributes of - the :class:`CookieJar`'s :class:`CookiePolicy` instance are true and false - respectively), the :mailheader:`Cookie2` header is also added when appropriate. - - The *request* object (usually a :class:`urllib2.Request` instance) must support - the methods :meth:`get_full_url`, :meth:`get_host`, :meth:`get_type`, - :meth:`unverifiable`, :meth:`get_origin_req_host`, :meth:`has_header`, - :meth:`get_header`, :meth:`header_items`, and :meth:`add_unredirected_header`,as - documented by :mod:`urllib2`. - - -.. method:: CookieJar.extract_cookies(response, request) - - Extract cookies from HTTP *response* and store them in the :class:`CookieJar`, - where allowed by policy. - - The :class:`CookieJar` will look for allowable :mailheader:`Set-Cookie` and - :mailheader:`Set-Cookie2` headers in the *response* argument, and store cookies - as appropriate (subject to the :meth:`CookiePolicy.set_ok` method's approval). - - The *response* object (usually the result of a call to :meth:`urllib2.urlopen`, - or similar) should support an :meth:`info` method, which returns an object with - a :meth:`getallmatchingheaders` method (usually a :class:`mimetools.Message` - instance). - - The *request* object (usually a :class:`urllib2.Request` instance) must support - the methods :meth:`get_full_url`, :meth:`get_host`, :meth:`unverifiable`, and - :meth:`get_origin_req_host`, as documented by :mod:`urllib2`. The request is - used to set default values for cookie-attributes as well as for checking that - the cookie is allowed to be set. - - -.. method:: CookieJar.set_policy(policy) - - Set the :class:`CookiePolicy` instance to be used. - - -.. method:: CookieJar.make_cookies(response, request) - - Return sequence of :class:`Cookie` objects extracted from *response* object. - - See the documentation for :meth:`extract_cookies` for the interfaces required of - the *response* and *request* arguments. - - -.. method:: CookieJar.set_cookie_if_ok(cookie, request) - - Set a :class:`Cookie` if policy says it's OK to do so. - - -.. method:: CookieJar.set_cookie(cookie) - - Set a :class:`Cookie`, without checking with policy to see whether or not it - should be set. - - -.. method:: 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 :exc:`KeyError` if no matching cookie exists. - - -.. method:: CookieJar.clear_session_cookies() - - Discard all session cookies. - - Discards all contained cookies that have a true :attr:`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 :meth:`save` method won't save session cookies anyway, unless you - ask otherwise by passing a true *ignore_discard* argument. - -:class:`FileCookieJar` implements the following additional methods: - - -.. method:: FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False) - - Save cookies to a file. - - This base class raises :exc:`NotImplementedError`. Subclasses may leave this - method unimplemented. - - *filename* is the name of file in which to save cookies. If *filename* is not - specified, :attr:`self.filename` is used (whose default is the value passed to - the constructor, if any); if :attr:`self.filename` is :const:`None`, - :exc:`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 :meth:`load` or - :meth:`revert` methods. - - -.. method:: 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 :meth:`save`. - - The named file must be in the format understood by the class, or - :exc:`LoadError` will be raised. Also, :exc:`IOError` may be raised, for - example if the file does not exist. - - .. note:: - - For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`), - :exc:`LoadError` is a subclass of :exc:`IOError`. - - -.. method:: FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False) - - Clear all cookies and reload cookies from a saved file. - - :meth:`revert` can raise the same exceptions as :meth:`load`. If there is a - failure, the object's state will not be altered. - -:class:`FileCookieJar` instances have the following public attributes: - - -.. attribute:: FileCookieJar.filename - - Filename of default file in which to keep cookies. This attribute may be - assigned to. - - -.. attribute:: 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 :class:`CookieJar` object may - ignore it. None of the :class:`FileCookieJar` classes included in the standard - library lazily loads cookies. - - -.. _file-cookie-jar-classes: - -FileCookieJar subclasses and co-operation with web browsers ------------------------------------------------------------ - -The following :class:`CookieJar` subclasses are provided for reading and writing -. Further :class:`CookieJar` subclasses, including one that reads Microsoft -Internet Explorer cookies, are available at -http://wwwsearch.sf.net/ClientCookie/. - - -.. class:: MozillaCookieJar(filename, delayload=None, policy=None) - - A :class:`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. - - -.. class:: LWPCookieJar(filename, delayload=None, policy=None) - - A :class:`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. - - -.. _cookie-policy-objects: - -CookiePolicy Objects --------------------- - -Objects implementing the :class:`CookiePolicy` interface have the following -methods: - - -.. method:: CookiePolicy.set_ok(cookie, request) - - Return boolean value indicating whether cookie should be accepted from server. - - *cookie* is a :class:`cookielib.Cookie` instance. *request* is an object - implementing the interface defined by the documentation for - :meth:`CookieJar.extract_cookies`. - - -.. method:: CookiePolicy.return_ok(cookie, request) - - Return boolean value indicating whether cookie should be returned to server. - - *cookie* is a :class:`cookielib.Cookie` instance. *request* is an object - implementing the interface defined by the documentation for - :meth:`CookieJar.add_cookie_header`. - - -.. method:: 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 :meth:`domain_return_ok` and :meth:`path_return_ok` leaves all the - work to :meth:`return_ok`. - - If :meth:`domain_return_ok` returns true for the cookie domain, - :meth:`path_return_ok` is called for the cookie path. Otherwise, - :meth:`path_return_ok` and :meth:`return_ok` are never called for that cookie - domain. If :meth:`path_return_ok` returns true, :meth:`return_ok` is called - with the :class:`Cookie` object itself for a full check. Otherwise, - :meth:`return_ok` is never called for that cookie path. - - Note that :meth:`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 :meth:`path_return_ok`. - - The *request* argument is as documented for :meth:`return_ok`. - - -.. method:: CookiePolicy.path_return_ok(path, request) - - Return false if cookies should not be returned, given cookie path. - - See the documentation for :meth:`domain_return_ok`. - -In addition to implementing the methods above, implementations of the -:class:`CookiePolicy` interface must also supply the following attributes, -indicating which protocols should be used, and how. All of these attributes may -be assigned to. - - -.. attribute:: CookiePolicy.netscape - - Implement Netscape protocol. - - -.. attribute:: CookiePolicy.rfc2965 - - Implement RFC 2965 protocol. - - -.. attribute:: CookiePolicy.hide_cookie2 - - Don't add :mailheader:`Cookie2` header to requests (the presence of this header - indicates to the server that we understand RFC 2965 cookies). - -The most useful way to define a :class:`CookiePolicy` class is by subclassing -from :class:`DefaultCookiePolicy` and overriding some or all of the methods -above. :class:`CookiePolicy` itself may be used as a 'null policy' to allow -setting and receiving any and all cookies (this is unlikely to be useful). - - -.. _default-cookie-policy-objects: - -DefaultCookiePolicy Objects ---------------------------- - -Implements the standard rules for accepting and returning cookies. - -Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is switched -off by default. - -The easiest way to provide your own policy is to override this class and call -its methods in your overridden implementations before adding your own additional -checks:: - - import cookielib - class MyCookiePolicy(cookielib.DefaultCookiePolicy): - def set_ok(self, cookie, request): - if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request): - return False - if i_dont_want_to_store_this_cookie(cookie): - return False - return True - -In addition to the features required to implement the :class:`CookiePolicy` -interface, this class allows you to block and allow domains from setting and -receiving cookies. There are also some strictness switches that allow you to -tighten up the rather loose Netscape protocol rules a little bit (at the cost of -blocking some benign cookies). - -A domain blacklist and whitelist is provided (both off by default). Only domains -not in the blacklist and present in the whitelist (if the whitelist is active) -participate in cookie setting and returning. Use the *blocked_domains* -constructor argument, and :meth:`blocked_domains` and -:meth:`set_blocked_domains` methods (and the corresponding argument and methods -for *allowed_domains*). If you set a whitelist, you can turn it off again by -setting it to :const:`None`. - -Domains in block or allow lists that do not start with a dot must equal the -cookie domain to be matched. For example, ``"example.com"`` matches a blacklist -entry of ``"example.com"``, but ``"www.example.com"`` does not. Domains that do -start with a dot are matched by more specific domains too. For example, both -``"www.example.com"`` and ``"www.coyote.example.com"`` match ``".example.com"`` -(but ``"example.com"`` itself does not). IP addresses are an exception, and -must match exactly. For example, if blocked_domains contains ``"192.168.1.2"`` -and ``".168.1.2"``, 192.168.1.2 is blocked, but 193.168.1.2 is not. - -:class:`DefaultCookiePolicy` implements the following additional methods: - - -.. method:: DefaultCookiePolicy.blocked_domains() - - Return the sequence of blocked domains (as a tuple). - - -.. method:: DefaultCookiePolicy.set_blocked_domains(blocked_domains) - - Set the sequence of blocked domains. - - -.. method:: DefaultCookiePolicy.is_blocked(domain) - - Return whether *domain* is on the blacklist for setting or receiving cookies. - - -.. method:: DefaultCookiePolicy.allowed_domains() - - Return :const:`None`, or the sequence of allowed domains (as a tuple). - - -.. method:: DefaultCookiePolicy.set_allowed_domains(allowed_domains) - - Set the sequence of allowed domains, or :const:`None`. - - -.. method:: DefaultCookiePolicy.is_not_allowed(domain) - - Return whether *domain* is not on the whitelist for setting or receiving - cookies. - -:class:`DefaultCookiePolicy` instances have the following attributes, which are -all initialised from the constructor arguments of the same name, and which may -all be assigned to. - - -.. attribute:: DefaultCookiePolicy.rfc2109_as_netscape - - If true, request that the :class:`CookieJar` instance downgrade RFC 2109 cookies - (ie. cookies received in a :mailheader:`Set-Cookie` header with a version - cookie-attribute of 1) to Netscape cookies by setting the version attribute of - the :class:`Cookie` instance to 0. The default value is :const:`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. - - -General strictness switches: - -.. attribute:: 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! - - -RFC 2965 protocol strictness switches: - -.. attribute:: 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 - - -Netscape protocol strictness switches: - -.. attribute:: DefaultCookiePolicy.strict_ns_unverifiable - - apply RFC 2965 rules on unverifiable transactions even to Netscape cookies - - -.. attribute:: DefaultCookiePolicy.strict_ns_domain - - Flags indicating how strict to be with domain-matching rules for Netscape - cookies. See below for acceptable values. - - -.. attribute:: DefaultCookiePolicy.strict_ns_set_initial_dollar - - Ignore cookies in Set-Cookie: headers that have names starting with ``'$'``. - - -.. attribute:: DefaultCookiePolicy.strict_ns_set_path - - Don't allow setting cookies whose path doesn't path-match request URI. - -:attr:`strict_ns_domain` is a collection of flags. Its value is constructed by -or-ing together (for example, ``DomainStrictNoDots|DomainStrictNonDomain`` means -both flags are set). - - -.. attribute:: 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). - - -.. attribute:: 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). - - -.. attribute:: DefaultCookiePolicy.DomainRFC2965Match - - When setting cookies, require a full RFC 2965 domain-match. - -The following attributes are provided for convenience, and are the most useful -combinations of the above flags: - - -.. attribute:: DefaultCookiePolicy.DomainLiberal - - Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched - off). - - -.. attribute:: DefaultCookiePolicy.DomainStrict - - Equivalent to ``DomainStrictNoDots|DomainStrictNonDomain``. - - -.. _cookielib-cookie-objects: - -Cookie Objects --------------- - -:class:`Cookie` instances have Python attributes roughly corresponding to the -standard cookie-attributes specified in the various cookie standards. The -correspondence is not one-to-one, because there are complicated rules for -assigning default values, because the ``max-age`` and ``expires`` -cookie-attributes contain equivalent information, and because RFC 2109 cookies -may be 'downgraded' by :mod:`cookielib` from version 1 to version 0 (Netscape) -cookies. - -Assignment to these attributes should not be necessary other than in rare -circumstances in a :class:`CookiePolicy` method. The class does not enforce -internal consistency, so you should know what you're doing if you do that. - - -.. attribute:: Cookie.version - - Integer or :const:`None`. Netscape cookies have :attr:`version` 0. RFC 2965 and - RFC 2109 cookies have a ``version`` cookie-attribute of 1. However, note that - :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which - case :attr:`version` is 0. - - -.. attribute:: Cookie.name - - Cookie name (a string). - - -.. attribute:: Cookie.value - - Cookie value (a string), or :const:`None`. - - -.. attribute:: Cookie.port - - String representing a port or a set of ports (eg. '80', or '80,8080'), or - :const:`None`. - - -.. attribute:: Cookie.path - - Cookie path (a string, eg. ``'/acme/rocket_launchers'``). - - -.. attribute:: Cookie.secure - - True if cookie should only be returned over a secure connection. - - -.. attribute:: Cookie.expires - - Integer expiry date in seconds since epoch, or :const:`None`. See also the - :meth:`is_expired` method. - - -.. attribute:: Cookie.discard - - True if this is a session cookie. - - -.. attribute:: Cookie.comment - - String comment from the server explaining the function of this cookie, or - :const:`None`. - - -.. attribute:: Cookie.comment_url - - URL linking to a comment from the server explaining the function of this cookie, - or :const:`None`. - - -.. attribute:: Cookie.rfc2109 - - True if this cookie was received as an RFC 2109 cookie (ie. the cookie - arrived in a :mailheader:`Set-Cookie` header, and the value of the Version - cookie-attribute in that header was 1). This attribute is provided because - :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in - which case :attr:`version` is 0. - - -.. attribute:: Cookie.port_specified - - True if a port or set of ports was explicitly specified by the server (in the - :mailheader:`Set-Cookie` / :mailheader:`Set-Cookie2` header). - - -.. attribute:: Cookie.domain_specified - - True if a domain was explicitly specified by the server. - - -.. attribute:: Cookie.domain_initial_dot - - True if the domain explicitly specified by the server began with a dot - (``'.'``). - -Cookies may have additional non-standard cookie-attributes. These may be -accessed using the following methods: - - -.. method:: Cookie.has_nonstandard_attr(name) - - Return true if cookie has the named cookie-attribute. - - -.. method:: Cookie.get_nonstandard_attr(name, default=None) - - If cookie has the named cookie-attribute, return its value. Otherwise, return - *default*. - - -.. method:: Cookie.set_nonstandard_attr(name, value) - - Set the value of the named cookie-attribute. - -The :class:`Cookie` class also defines the following method: - - -.. method:: Cookie.is_expired([now=:const:`None`]) - - True if cookie has passed the time at which the server requested it should - expire. If *now* is given (in seconds since the epoch), return whether the - cookie has expired at the specified time. - - -.. _cookielib-examples: - -Examples --------- - -The first example shows the most common usage of :mod:`cookielib`:: - - import cookielib, urllib2 - cj = cookielib.CookieJar() - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - r = opener.open("http://example.com/") - -This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx -cookies (assumes Unix/Netscape convention for location of the cookies file):: - - import os, cookielib, urllib2 - cj = cookielib.MozillaCookieJar() - cj.load(os.path.join(os.environ["HOME"], ".netscape/cookies.txt")) - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - r = opener.open("http://example.com/") - -The next example illustrates the use of :class:`DefaultCookiePolicy`. Turn on -RFC 2965 cookies, be more strict about domains when setting and returning -Netscape cookies, and block some domains from setting cookies or having them -returned:: - - import urllib2 - from cookielib import CookieJar, DefaultCookiePolicy - policy = DefaultCookiePolicy( - rfc2965=True, strict_ns_domain=Policy.DomainStrict, - blocked_domains=["ads.net", ".ads.net"]) - cj = CookieJar(policy) - opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) - r = opener.open("http://example.com/") - Index: Doc/library/httplib.rst =================================================================== --- Doc/library/httplib.rst (revisão 62992) +++ Doc/library/httplib.rst (cópia de trabalho) @@ -1,501 +0,0 @@ - -:mod:`httplib` --- HTTP protocol client -======================================= - -.. module:: httplib - :synopsis: HTTP and HTTPS protocol client (requires sockets). - - -.. index:: - pair: HTTP; protocol - single: HTTP; httplib (standard module) - -.. index:: module: urllib - -This module defines classes which implement the client side of the HTTP and -HTTPS protocols. It is normally not used directly --- the module :mod:`urllib` -uses it to handle URLs that use HTTP and HTTPS. - -.. note:: - - HTTPS support is only available if the :mod:`socket` module was compiled with - SSL support. - -The module provides the following classes: - - -.. class:: HTTPConnection(host[, port[, strict[, timeout]]]) - - An :class:`HTTPConnection` instance represents one transaction with an HTTP - server. It should be instantiated passing it a host and optional port number. - If no port number is passed, the port is extracted from the host string if it - has the form ``host:port``, else the default HTTP port (80) is used. When True, - the optional parameter *strict* causes ``BadStatusLine`` to be raised if the - status line can't be parsed as a valid HTTP/1.0 or 1.1 status line. If the - optional *timeout* parameter is given, connection attempts will timeout after - that many seconds (if it is not given or ``None``, the global default timeout - setting is used). - - For example, the following calls all create instances that connect to the server - at the same host and port:: - - >>> h1 = httplib.HTTPConnection('www.cwi.nl') - >>> h2 = httplib.HTTPConnection('www.cwi.nl:80') - >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80) - >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10) - - -.. class:: HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout]]]]]) - - A subclass of :class:`HTTPConnection` that uses SSL for communication with - secure servers. Default port is ``443``. *key_file* is the name of a PEM - formatted file that contains your private key. *cert_file* is a PEM formatted - certificate chain file. - - .. warning:: - - This does not do any certificate verification! - - -.. class:: HTTPResponse(sock[, debuglevel=0][, strict=0]) - - Class whose instances are returned upon successful connection. Not instantiated - directly by user. - - -The following exceptions are raised as appropriate: - - -.. exception:: HTTPException - - The base class of the other exceptions in this module. It is a subclass of - :exc:`Exception`. - - -.. exception:: NotConnected - - A subclass of :exc:`HTTPException`. - - -.. exception:: InvalidURL - - A subclass of :exc:`HTTPException`, raised if a port is given and is either - non-numeric or empty. - - -.. exception:: UnknownProtocol - - A subclass of :exc:`HTTPException`. - - -.. exception:: UnknownTransferEncoding - - A subclass of :exc:`HTTPException`. - - -.. exception:: UnimplementedFileMode - - A subclass of :exc:`HTTPException`. - - -.. exception:: IncompleteRead - - A subclass of :exc:`HTTPException`. - - -.. exception:: ImproperConnectionState - - A subclass of :exc:`HTTPException`. - - -.. exception:: CannotSendRequest - - A subclass of :exc:`ImproperConnectionState`. - - -.. exception:: CannotSendHeader - - A subclass of :exc:`ImproperConnectionState`. - - -.. exception:: ResponseNotReady - - A subclass of :exc:`ImproperConnectionState`. - - -.. exception:: BadStatusLine - - A subclass of :exc:`HTTPException`. Raised if a server responds with a HTTP - status code that we don't understand. - -The constants defined in this module are: - - -.. data:: HTTP_PORT - - The default port for the HTTP protocol (always ``80``). - - -.. data:: HTTPS_PORT - - The default port for the HTTPS protocol (always ``443``). - -and also the following constants for integer status codes: - -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| Constant | Value | Definition | -+==========================================+=========+=======================================================================+ -| :const:`CONTINUE` | ``100`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.1.1 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`SWITCHING_PROTOCOLS` | ``101`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.1.2 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`PROCESSING` | ``102`` | WEBDAV, `RFC 2518, Section 10.1 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`OK` | ``200`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.1 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`CREATED` | ``201`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.2 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`ACCEPTED` | ``202`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.3 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NON_AUTHORITATIVE_INFORMATION` | ``203`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.4 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NO_CONTENT` | ``204`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.5 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`RESET_CONTENT` | ``205`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.6 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`PARTIAL_CONTENT` | ``206`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.2.7 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`MULTI_STATUS` | ``207`` | WEBDAV `RFC 2518, Section 10.2 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`IM_USED` | ``226`` | Delta encoding in HTTP, | -| | | :rfc:`3229`, Section 10.4.1 | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`MULTIPLE_CHOICES` | ``300`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.1 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`MOVED_PERMANENTLY` | ``301`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.2 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`FOUND` | ``302`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.3 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`SEE_OTHER` | ``303`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.4 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NOT_MODIFIED` | ``304`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.5 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`USE_PROXY` | ``305`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.6 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`TEMPORARY_REDIRECT` | ``307`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.3.8 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`BAD_REQUEST` | ``400`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.1 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`UNAUTHORIZED` | ``401`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.2 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`PAYMENT_REQUIRED` | ``402`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.3 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`FORBIDDEN` | ``403`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.4 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NOT_FOUND` | ``404`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.5 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`METHOD_NOT_ALLOWED` | ``405`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.6 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NOT_ACCEPTABLE` | ``406`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.7 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`PROXY_AUTHENTICATION_REQUIRED` | ``407`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.8 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`REQUEST_TIMEOUT` | ``408`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.9 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`CONFLICT` | ``409`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.10 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`GONE` | ``410`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.11 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`LENGTH_REQUIRED` | ``411`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.12 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`PRECONDITION_FAILED` | ``412`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.13 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`REQUEST_ENTITY_TOO_LARGE` | ``413`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.14 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`REQUEST_URI_TOO_LONG` | ``414`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.15 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`UNSUPPORTED_MEDIA_TYPE` | ``415`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.16 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`REQUESTED_RANGE_NOT_SATISFIABLE` | ``416`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.17 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`EXPECTATION_FAILED` | ``417`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.4.18 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`UNPROCESSABLE_ENTITY` | ``422`` | WEBDAV, `RFC 2518, Section 10.3 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`LOCKED` | ``423`` | WEBDAV `RFC 2518, Section 10.4 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`FAILED_DEPENDENCY` | ``424`` | WEBDAV, `RFC 2518, Section 10.5 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`UPGRADE_REQUIRED` | ``426`` | HTTP Upgrade to TLS, | -| | | :rfc:`2817`, Section 6 | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`INTERNAL_SERVER_ERROR` | ``500`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.5.1 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NOT_IMPLEMENTED` | ``501`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.5.2 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`BAD_GATEWAY` | ``502`` | HTTP/1.1 `RFC 2616, Section | -| | | 10.5.3 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`SERVICE_UNAVAILABLE` | ``503`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.5.4 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`GATEWAY_TIMEOUT` | ``504`` | HTTP/1.1 `RFC 2616, Section | -| | | 10.5.5 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`HTTP_VERSION_NOT_SUPPORTED` | ``505`` | HTTP/1.1, `RFC 2616, Section | -| | | 10.5.6 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`INSUFFICIENT_STORAGE` | ``507`` | WEBDAV, `RFC 2518, Section 10.6 | -| | | `_ | -+------------------------------------------+---------+-----------------------------------------------------------------------+ -| :const:`NOT_EXTENDED` | ``510`` | An HTTP Extension Framework, | -| | | :rfc:`2774`, Section 7 | -+------------------------------------------+---------+-----------------------------------------------------------------------+ - - -.. data:: responses - - This dictionary maps the HTTP 1.1 status codes to the W3C names. - - Example: ``httplib.responses[httplib.NOT_FOUND]`` is ``'Not Found'``. - - -.. _httpconnection-objects: - -HTTPConnection Objects ----------------------- - -:class:`HTTPConnection` instances have the following methods: - - -.. method:: HTTPConnection.request(method, url[, body[, headers]]) - - This will send a request to the server using the HTTP request method *method* - and the selector *url*. If the *body* argument is present, it should be a - string of data to send after the headers are finished. Alternatively, it may - be an open file object, in which case the contents of the file is sent; this - file object should support ``fileno()`` and ``read()`` methods. The header - Content-Length is automatically set to the correct value. The *headers* - argument should be a mapping of extra HTTP headers to send with the request. - - -.. method:: HTTPConnection.getresponse() - - Should be called after a request is sent to get the response from the server. - Returns an :class:`HTTPResponse` instance. - - .. note:: - - Note that you must have read the whole response before you can send a new - request to the server. - - -.. method:: HTTPConnection.set_debuglevel(level) - - Set the debugging level (the amount of debugging output printed). The default - debug level is ``0``, meaning no debugging output is printed. - - -.. method:: HTTPConnection.connect() - - Connect to the server specified when the object was created. - - -.. method:: HTTPConnection.close() - - Close the connection to the server. - -As an alternative to using the :meth:`request` method described above, you can -also send your request step by step, by using the four functions below. - - -.. method:: HTTPConnection.putrequest(request, selector[, skip_host[, skip_accept_encoding]]) - - This should be the first call after the connection to the server has been made. - It sends a line to the server consisting of the *request* string, the *selector* - string, and the HTTP version (``HTTP/1.1``). To disable automatic sending of - ``Host:`` or ``Accept-Encoding:`` headers (for example to accept additional - content encodings), specify *skip_host* or *skip_accept_encoding* with non-False - values. - - -.. method:: HTTPConnection.putheader(header, argument[, ...]) - - Send an :rfc:`822`\ -style header to the server. It sends a line to the server - consisting of the header, a colon and a space, and the first argument. If more - arguments are given, continuation lines are sent, each consisting of a tab and - an argument. - - -.. method:: HTTPConnection.endheaders() - - Send a blank line to the server, signalling the end of the headers. - - -.. method:: HTTPConnection.send(data) - - Send data to the server. This should be used directly only after the - :meth:`endheaders` method has been called and before :meth:`getresponse` is - called. - - -.. _httpresponse-objects: - -HTTPResponse Objects --------------------- - -:class:`HTTPResponse` instances have the following methods and attributes: - - -.. method:: HTTPResponse.read([amt]) - - Reads and returns the response body, or up to the next *amt* bytes. - - -.. method:: HTTPResponse.getheader(name[, default]) - - Get the contents of the header *name*, or *default* if there is no matching - header. - - -.. method:: HTTPResponse.getheaders() - - Return a list of (header, value) tuples. - - -.. attribute:: HTTPResponse.msg - - A :class:`mimetools.Message` instance containing the response headers. - - -.. attribute:: HTTPResponse.version - - HTTP protocol version used by server. 10 for HTTP/1.0, 11 for HTTP/1.1. - - -.. attribute:: HTTPResponse.status - - Status code returned by server. - - -.. attribute:: HTTPResponse.reason - - Reason phrase returned by server. - - -.. _httplib-examples: - -Examples --------- - -Here is an example session that uses the ``GET`` method:: - - >>> import httplib - >>> conn = httplib.HTTPConnection("www.python.org") - >>> conn.request("GET", "/index.html") - >>> r1 = conn.getresponse() - >>> print(r1.status, r1.reason) - 200 OK - >>> data1 = r1.read() - >>> conn.request("GET", "/parrot.spam") - >>> r2 = conn.getresponse() - >>> print(r2.status, r2.reason) - 404 Not Found - >>> data2 = r2.read() - >>> conn.close() - -Here is an example session that shows how to ``POST`` requests:: - - >>> import httplib, urllib - >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) - >>> headers = {"Content-type": "application/x-www-form-urlencoded", - ... "Accept": "text/plain"} - >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") - >>> conn.request("POST", "/cgi-bin/query", params, headers) - >>> response = conn.getresponse() - >>> print(response.status, response.reason) - 200 OK - >>> data = response.read() - >>> conn.close() - Index: Doc/library/xmlrpclib.rst =================================================================== --- Doc/library/xmlrpclib.rst (revisão 62992) +++ Doc/library/xmlrpclib.rst (cópia de trabalho) @@ -533,14 +533,14 @@ :: - import xmlrpclib, httplib + import xmlrpclib, http.client class ProxiedTransport(xmlrpclib.Transport): def set_proxy(self, proxy): self.proxy = proxy def make_connection(self, host): self.realhost = host - h = httplib.HTTP(self.proxy) + h = http.client.HTTP(self.proxy) return h def send_request(self, connection, handler, request_body): connection.putrequest("POST", 'http://%s%s' % (self.realhost, handler)) Index: Doc/library/http.cookies.rst =================================================================== --- Doc/library/http.cookies.rst (revisão 62992) +++ Doc/library/http.cookies.rst (cópia de trabalho) @@ -1,14 +1,14 @@ -:mod:`Cookie` --- HTTP state management +:mod:`http.cookies` --- HTTP state management ======================================= -.. module:: Cookie +.. module:: http.cookies :synopsis: Support for HTTP state management (cookies). .. moduleauthor:: Timothy O'Malley .. sectionauthor:: Moshe Zadka -The :mod:`Cookie` module defines classes for abstracting the concept of +The :mod:`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. @@ -63,7 +63,7 @@ The same security warning from :class:`SerialCookie` applies here. A further security note is warranted. For backwards compatibility, the -:mod:`Cookie` module exports a class named :class:`Cookie` which is just an +:mod:`http.cookies` module exports a class named :class:`Cookie` which is just an alias for :class:`SmartCookie`. This is probably a mistake and will likely be removed in a future version. You should not use the :class:`Cookie` class in your applications, for the same reason why you should not use the @@ -72,8 +72,8 @@ .. seealso:: - Module :mod:`cookielib` - HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie` + Module :mod:`http.cookiejar` + HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and :mod:`http.cookies` modules do not depend on each other. :rfc:`2109` - HTTP State Management Mechanism @@ -211,10 +211,10 @@ .. doctest:: :options: +NORMALIZE_WHITESPACE - >>> import Cookie - >>> C = Cookie.SimpleCookie() - >>> C = Cookie.SerialCookie() - >>> C = Cookie.SmartCookie() + >>> import http.cookies + >>> C = http.cookies.SimpleCookie() + >>> C = http.cookies.SerialCookie() + >>> C = http.cookies.SmartCookie() >>> C["fig"] = "newton" >>> C["sugar"] = "wafer" >>> print(C) # generate HTTP headers @@ -223,32 +223,32 @@ >>> print(C.output()) # same thing Set-Cookie: fig=newton Set-Cookie: sugar=wafer - >>> C = Cookie.SmartCookie() + >>> C = http.cookies.SmartCookie() >>> 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 = Cookie.SmartCookie() + >>> C = http.cookies.SmartCookie() >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) >>> print(C) Set-Cookie: chips=ahoy Set-Cookie: vienna=finger - >>> C = Cookie.SmartCookie() + >>> C = http.cookies.SmartCookie() >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";') >>> print(C) Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;" - >>> C = Cookie.SmartCookie() + >>> C = http.cookies.SmartCookie() >>> C["oreo"] = "doublestuff" >>> C["oreo"]["path"] = "/" >>> print(C) Set-Cookie: oreo=doublestuff; Path=/ - >>> C = Cookie.SmartCookie() + >>> C = http.cookies.SmartCookie() >>> C["twix"] = "none for you" >>> C["twix"].value 'none for you' - >>> C = Cookie.SimpleCookie() + >>> C = http.cookies.SimpleCookie() >>> C["number"] = 7 # equivalent to C["number"] = str(7) >>> C["string"] = "seven" >>> C["number"].value @@ -258,7 +258,7 @@ >>> print(C) Set-Cookie: number=7 Set-Cookie: string=seven - >>> C = Cookie.SerialCookie() + >>> C = http.cookies.SerialCookie() >>> C["number"] = 7 >>> C["string"] = "seven" >>> C["number"].value @@ -268,7 +268,7 @@ >>> print(C) Set-Cookie: number="I7\012." Set-Cookie: string="S'seven'\012p1\012." - >>> C = Cookie.SmartCookie() + >>> C = http.cookies.SmartCookie() >>> C["number"] = 7 >>> C["string"] = "seven" >>> C["number"].value Index: Doc/library/http.server.rst =================================================================== --- Doc/library/http.server.rst (revisão 0) +++ Doc/library/http.server.rst (revisão 0) @@ -0,0 +1,371 @@ + +:mod:`http.server` --- HTTP server module +========================================= + +.. module:: http.server + :synopsis: This package has a Basic HTTP server class, + a request handler for HTTP servers which can run CGI + and a basic request handler for HTTP servers. + +.. sectionauthor:: Moshe Zadka + +.. index:: + pair: WWW; server + pair: HTTP; protocol + single: URL + single: httpd + +The first class, :class:`HTTPServer`, is a :class:`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=http.server.HTTPServer, + handler_class=http.server.BaseHTTPRequestHandler): + server_address = ('', 8000) + httpd = server_class(server_address, handler_class) + httpd.serve_forever() + + +.. class:: HTTPServer(server_address, RequestHandlerClass) + + This class builds on the :class:`TCPServer` class by storing the server + address as instance variables named :attr:`server_name` and + :attr:`server_port`. The server is accessible by the handler, typically + through the handler's :attr:`server` instance variable. + + +.. class:: 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). :class:`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 :meth:`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 :meth:`__init__` method. + + :class:`BaseHTTPRequestHandler` has the following instance variables: + + + .. attribute:: client_address + + Contains a tuple of the form ``(host, port)`` referring to the client's + address. + + + .. attribute:: command + + Contains the command (request type). For example, ``'GET'``. + + + .. attribute:: path + + Contains the request path. + + + .. attribute:: request_version + + Contains the version string from the request. For example, ``'HTTP/1.0'``. + + + .. attribute:: headers + + Holds an instance of the class specified by the :attr:`MessageClass` class + variable. This instance parses and manages the headers in the HTTP + request. + + + .. attribute:: rfile + + Contains an input stream, positioned at the start of the optional input + data. + + + .. attribute:: 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. + + + :class:`BaseHTTPRequestHandler` has the following class variables: + + + .. attribute:: 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'``. + + + .. attribute:: sys_version + + Contains the Python system version, in a form usable by the + :attr:`version_string` method and the :attr:`server_version` class + variable. For example, ``'Python/1.4'``. + + + .. attribute:: error_message_format + + Specifies a format string for building an error response to the client. It + uses parenthesized, keyed format specifiers, so the format operand must be + a dictionary. The *code* key should be an integer, specifying the numeric + HTTP error code value. *message* should be a string containing a + (detailed) error message of what occurred, and *explain* should be an + explanation of the error code number. Default *message* and *explain* + values can found in the *responses* class variable. + + + .. attribute:: error_content_type + + Specifies the Content-Type HTTP header of error responses sent to the + client. The default value is ``'text/html'``. + + + .. attribute:: 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 :meth:`send_header`) in all of its responses to clients. + For backwards compatibility, the setting defaults to ``'HTTP/1.0'``. + + + .. attribute:: MessageClass + + .. index:: single: Message (in module mimetools) + + Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. + Typically, this is not overridden, and it defaults to + :class:`mimetools.Message`. + + + .. attribute:: responses + + This variable 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 (see the + :attr:`error_message_format` class variable). + + + A :class:`BaseHTTPRequestHandler` instance has the following methods: + + + .. method:: handle() + + Calls :meth:`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 :meth:`do_\*` + methods. + + + .. method:: handle_one_request() + + This method will parse and dispatch the request to the appropriate + :meth:`do_\*` method. You should never need to override it. + + + .. method:: send_error(code[, message]) + + Sends and logs a complete error reply to the client. The numeric *code* + specifies the HTTP error code, with *message* as optional, more specific text. A + complete set of headers is sent, followed by text composed using the + :attr:`error_message_format` class variable. + + + .. method:: send_response(code[, message]) + + Sends a response header and logs the accepted request. The HTTP response + line is sent, followed by *Server* and *Date* headers. The values for + these two headers are picked up from the :meth:`version_string` and + :meth:`date_time_string` methods, respectively. + + + .. method:: send_header(keyword, value) + + Writes a specific HTTP header to the output stream. *keyword* should + specify the header keyword, with *value* specifying its value. + + + .. method:: end_headers() + + Sends a blank line, indicating the end of the HTTP headers in the + response. + + + .. method:: 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. + + + .. method:: log_error(...) + + Logs an error when a request cannot be fulfilled. By default, it passes + the message to :meth:`log_message`, so it takes the same arguments + (*format* and additional values). + + + .. method:: 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 + :meth:`log_message` are applied as inputs to the formatting. The client + address and current date and time are prefixed to every message logged. + + + .. method:: version_string() + + Returns the server software's version string. This is a combination of the + :attr:`server_version` and :attr:`sys_version` class variables. + + + .. method:: date_time_string([timestamp]) + + Returns the date and time given by *timestamp* (which must be in the + format returned by :func:`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'``. + + + .. method:: log_date_time_string() + + Returns the current date and time, formatted for logging. + + + .. method:: address_string() + + Returns the client address, formatted for logging. A name lookup is + performed on the client's IP address. + +Class :class:`CGIHTTPRequestHandler` for a request handler for HTTP servers +which can run CGI, interface compatible with :class:`BaseHTTPRequestHandler` +and inherits behavior from :class:`SimpleHTTPRequestHandler` but can also +run CGI scripts. + +.. note:: + + This class can run CGI scripts on Unix and Windows systems; on Mac OS it will + only be able to run Python scripts within the same process as itself. + +.. note:: + + CGI scripts run by the :class:`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. + + +.. class:: 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 + :class:`SimpleHTTPRequestHandler`. + + 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 :func:`do_GET` and :func:`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 :class:`CGIHTTPRequestHandler` defines the following data member: + + + .. attribute:: cgi_directories + + This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to + treat as containing CGI scripts. + + The :class:`CGIHTTPRequestHandler` defines the following methods: + + + .. 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. + +For example usage, see the implementation of the :func:`test` function. + +The class :class:`SimpleHTTPRequestHandler`, which is interface-compatible with +:class:`BaseHTTPRequestHandler`. + +.. class:: SimpleHTTPRequestHandler(request, client_address, server) + + 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 + :class:`http.server.BaseHTTPRequestHandler`. This class implements the + :func:`do_GET` and :func:`do_HEAD` functions. + + The following are defined as class-level attributes of + :class:`SimpleHTTPRequestHandler`: + + + .. attribute:: server_version + + This will be ``"SimpleHTTP/" + __version__``, where ``__version__`` is + defined at the module level. + + + .. attribute:: extensions_map + + A dictionary mapping suffixes into MIME types. The default is + signified by an empty string, and is considered to be + ``application/octet-stream``. The mapping is used case-insensitively, + and so should contain only lower-cased keys. + + The :class:`SimpleHTTPRequestHandler` class defines the following methods: + + + .. method:: do_HEAD() + + This method serves the ``'HEAD'`` request type: it sends the headers it + would send for the equivalent ``GET`` request. See the :meth:`do_GET` + method for a more complete explanation of the possible headers. + + + .. method:: 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 :meth:`list_directory` method. This method uses + :func:`os.listdir` to scan the directory, and returns a ``404`` error + response if the :func:`listdir` fails. + + If the request was mapped to a file, it is opened and the contents are + returned. Any :exc:`IOError` exception in opening the requested file is + mapped to a ``404``, ``'File not found'`` error. Otherwise, the content + type is guessed by calling the :meth:`guess_type` method, which in turn + uses the *extensions_map* variable. + + 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 :func:`test` function. + Index: Doc/library/codecs.rst =================================================================== --- Doc/library/codecs.rst (revisão 62992) +++ Doc/library/codecs.rst (cópia de trabalho) @@ -1174,8 +1174,8 @@ transparently converts Unicode host names to ACE, so that applications need not be concerned about converting host names themselves when they pass them to the socket module. On top of that, modules that have host names as function -parameters, such as :mod:`httplib` and :mod:`ftplib`, accept Unicode host names -(:mod:`httplib` then also transparently sends an IDNA hostname in the +parameters, such as :mod:`http.client` and :mod:`ftplib`, accept Unicode host names +(:mod:`http.client` then also transparently sends an IDNA hostname in the :mailheader:`Host` field if it sends that field at all). When receiving host names from the wire (such as in reverse name lookup), no Index: Doc/library/ssl.rst =================================================================== --- Doc/library/ssl.rst (revisão 62992) +++ Doc/library/ssl.rst (cópia de trabalho) @@ -489,7 +489,7 @@ pprint.pprint(ssl_sock.getpeercert()) print(pprint.pformat(ssl_sock.getpeercert())) - # Set a simple HTTP request -- use httplib in actual code. + # Set a simple HTTP request -- use http.client in actual code. ssl_sock.write("""GET / HTTP/1.0\r Host: www.verisign.com\r\n\r\n""") Index: Doc/library/wsgiref.rst =================================================================== --- Doc/library/wsgiref.rst (revisão 62992) +++ Doc/library/wsgiref.rst (cópia de trabalho) @@ -260,7 +260,7 @@ :synopsis: A simple WSGI HTTP server. -This module implements a simple HTTP server (based on :mod:`BaseHTTPServer`) +This module implements a simple HTTP server (based on :mod:`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 @@ -303,13 +303,13 @@ Create a :class:`WSGIServer` instance. *server_address* should be a ``(host,port)`` tuple, and *RequestHandlerClass* should be the subclass of - :class:`BaseHTTPServer.BaseHTTPRequestHandler` that will be used to process + :class:`http.server.BaseHTTPRequestHandler` that will be used to process requests. You do not normally need to call this constructor, as the :func:`make_server` function can handle all the details for you. - :class:`WSGIServer` is a subclass of :class:`BaseHTTPServer.HTTPServer`, so all + :class:`WSGIServer` is a subclass of :class:`http.server.HTTPServer`, so all of its methods (such as :meth:`serve_forever` and :meth:`handle_request`) are available. :class:`WSGIServer` also provides these WSGI-specific methods: Index: Doc/library/http.cookiejar.rst =================================================================== --- Doc/library/http.cookiejar.rst (revisão 62992) +++ Doc/library/http.cookiejar.rst (cópia de trabalho) @@ -1,14 +1,14 @@ -:mod:`cookielib` --- Cookie handling for HTTP clients +:mod:`http.cookiejar` --- Cookie handling for HTTP clients ===================================================== -.. module:: cookielib +.. module:: http.cookiejar :synopsis: Classes for automatic handling of HTTP cookies. .. moduleauthor:: John J. Lee .. sectionauthor:: John J. Lee -The :mod:`cookielib` module defines classes for automatic handling of HTTP +The :mod:`http.cookiejar` module defines classes for automatic handling of HTTP cookies. It is useful for accessing web sites that require small pieces of data -- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a web server, and then returned to the server in later HTTP requests. @@ -18,7 +18,7 @@ :rfc:`2109` cookies are parsed as Netscape cookies and subsequently treated either as Netscape or RFC 2965 cookies according to the 'policy' in effect. Note that the great majority of cookies on the Internet are Netscape cookies. -:mod:`cookielib` attempts to follow the de-facto Netscape cookie protocol (which +:mod:`http.cookiejar` attempts to follow the de-facto Netscape cookie protocol (which differs substantially from that set out in the original Netscape specification), including taking note of the ``max-age`` and ``port`` cookie-attributes introduced with RFC 2965. @@ -99,7 +99,7 @@ .. class:: Cookie() This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not - expected that users of :mod:`cookielib` construct their own :class:`Cookie` + expected that users of :mod:`http.cookiejar` construct their own :class:`Cookie` instances. Instead, if necessary, call :meth:`make_cookies` on a :class:`CookieJar` instance. @@ -111,7 +111,7 @@ Module :mod:`Cookie` HTTP cookie classes, principally useful for server-side code. The - :mod:`cookielib` and :mod:`Cookie` modules do not depend on each other. + :mod:`http.cookiejar` and :mod:`Cookie` modules do not depend on each other. http://wwwsearch.sf.net/ClientCookie/ Extensions to this module, including a class for reading Microsoft Internet @@ -120,7 +120,7 @@ http://wp.netscape.com/newsref/std/cookie_spec.html The specification of the original Netscape cookie protocol. Though this is still the dominant protocol, the 'Netscape cookie protocol' implemented by all - the major browsers (and :mod:`cookielib`) only bears a passing resemblance to + the major browsers (and :mod:`http.cookiejar`) only bears a passing resemblance to the one sketched out in ``cookie_spec.html``. :rfc:`2109` - HTTP State Management Mechanism @@ -349,7 +349,7 @@ Return boolean value indicating whether cookie should be accepted from server. - *cookie* is a :class:`cookielib.Cookie` instance. *request* is an object + *cookie* is a :class:`http.cookiejar.Cookie` instance. *request* is an object implementing the interface defined by the documentation for :meth:`CookieJar.extract_cookies`. @@ -358,7 +358,7 @@ Return boolean value indicating whether cookie should be returned to server. - *cookie* is a :class:`cookielib.Cookie` instance. *request* is an object + *cookie* is a :class:`http.cookiejar.Cookie` instance. *request* is an object implementing the interface defined by the documentation for :meth:`CookieJar.add_cookie_header`. @@ -434,10 +434,10 @@ its methods in your overridden implementations before adding your own additional checks:: - import cookielib - class MyCookiePolicy(cookielib.DefaultCookiePolicy): + import http.cookiejar + class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy): def set_ok(self, cookie, request): - if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request): + if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request): return False if i_dont_want_to_store_this_cookie(cookie): return False @@ -594,7 +594,7 @@ Equivalent to ``DomainStrictNoDots|DomainStrictNonDomain``. -.. _cookielib-cookie-objects: +.. _http.cookiejar-cookie-objects: Cookie Objects -------------- @@ -604,7 +604,7 @@ correspondence is not one-to-one, because there are complicated rules for assigning default values, because the ``max-age`` and ``expires`` cookie-attributes contain equivalent information, and because RFC 2109 cookies -may be 'downgraded' by :mod:`cookielib` from version 1 to version 0 (Netscape) +may be 'downgraded' by :mod:`http.cookiejar` from version 1 to version 0 (Netscape) cookies. Assignment to these attributes should not be necessary other than in rare @@ -616,7 +616,7 @@ Integer or :const:`None`. Netscape cookies have :attr:`version` 0. RFC 2965 and RFC 2109 cookies have a ``version`` cookie-attribute of 1. However, note that - :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which + :mod:`http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which case :attr:`version` is 0. @@ -674,7 +674,7 @@ True if this cookie was received as an RFC 2109 cookie (ie. the cookie arrived in a :mailheader:`Set-Cookie` header, and the value of the Version cookie-attribute in that header was 1). This attribute is provided because - :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in + :mod:`http.cookiejar` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which case :attr:`version` is 0. @@ -723,23 +723,23 @@ cookie has expired at the specified time. -.. _cookielib-examples: +.. _http.cookiejar-examples: Examples -------- -The first example shows the most common usage of :mod:`cookielib`:: +The first example shows the most common usage of :mod:`http.cookiejar`:: - import cookielib, urllib2 - cj = cookielib.CookieJar() + import http.cookiejar, urllib2 + cj = http.cookiejar.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx cookies (assumes Unix/Netscape convention for location of the cookies file):: - import os, cookielib, urllib2 - cj = cookielib.MozillaCookieJar() + import os, http.cookiejar, urllib2 + cj = http.cookiejar.MozillaCookieJar() cj.load(os.path.join(os.environ["HOME"], ".netscape/cookies.txt")) opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") @@ -750,7 +750,7 @@ returned:: import urllib2 - from cookielib import CookieJar, DefaultCookiePolicy + from http.cookiejar import CookieJar, DefaultCookiePolicy policy = DefaultCookiePolicy( rfc2965=True, strict_ns_domain=Policy.DomainStrict, blocked_domains=["ads.net", ".ads.net"]) Index: Doc/library/cgihttpserver.rst =================================================================== --- Doc/library/cgihttpserver.rst (revisão 62992) +++ Doc/library/cgihttpserver.rst (cópia de trabalho) @@ -1,73 +0,0 @@ - -:mod:`CGIHTTPServer` --- CGI-capable HTTP request handler -========================================================= - -.. module:: CGIHTTPServer - :synopsis: This module provides a request handler for HTTP servers which can run CGI - scripts. -.. sectionauthor:: Moshe Zadka - - -The :mod:`CGIHTTPServer` module defines a request-handler class, interface -compatible with :class:`BaseHTTPServer.BaseHTTPRequestHandler` and inherits -behavior from :class:`SimpleHTTPServer.SimpleHTTPRequestHandler` but can also -run CGI scripts. - -.. note:: - - This module can run CGI scripts on Unix and Windows systems; on Mac OS it will - only be able to run Python scripts within the same process as itself. - -.. note:: - - CGI scripts run by the :class:`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 :mod:`CGIHTTPServer` module defines the following class: - - -.. class:: 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 - :class:`SimpleHTTPServer.SimpleHTTPRequestHandler`. - - 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 :func:`do_GET` and :func:`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 :class:`CGIHTTPRequestHandler` defines the following data member: - - - .. attribute:: cgi_directories - - This defaults to ``['/cgi-bin', '/htbin']`` and describes directories to - treat as containing CGI scripts. - - The :class:`CGIHTTPRequestHandler` defines the following methods: - - - .. 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. - -For example usage, see the implementation of the :func:`test` function. - - -.. seealso:: - - Module :mod:`BaseHTTPServer` - Base class implementation for Web server and request handler. - Index: Doc/library/basehttpserver.rst =================================================================== --- Doc/library/basehttpserver.rst (revisão 62992) +++ Doc/library/basehttpserver.rst (cópia de trabalho) @@ -1,265 +0,0 @@ - -:mod:`BaseHTTPServer` --- Basic HTTP server -=========================================== - -.. module:: BaseHTTPServer - :synopsis: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer). - - -.. index:: - pair: WWW; server - pair: HTTP; protocol - single: URL - single: httpd - -.. index:: - module: SimpleHTTPServer - module: CGIHTTPServer - -This module defines two classes for implementing HTTP servers (Web servers). -Usually, this module isn't used directly, but is used as a basis for building -functioning Web servers. See the :mod:`SimpleHTTPServer` and -:mod:`CGIHTTPServer` modules. - -The first class, :class:`HTTPServer`, is a :class:`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=BaseHTTPServer.HTTPServer, - handler_class=BaseHTTPServer.BaseHTTPRequestHandler): - server_address = ('', 8000) - httpd = server_class(server_address, handler_class) - httpd.serve_forever() - - -.. class:: HTTPServer(server_address, RequestHandlerClass) - - This class builds on the :class:`TCPServer` class by storing the server - address as instance variables named :attr:`server_name` and - :attr:`server_port`. The server is accessible by the handler, typically - through the handler's :attr:`server` instance variable. - - -.. class:: 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). :class:`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 :meth:`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 :meth:`__init__` method. - - :class:`BaseHTTPRequestHandler` has the following instance variables: - - - .. attribute:: client_address - - Contains a tuple of the form ``(host, port)`` referring to the client's - address. - - - .. attribute:: command - - Contains the command (request type). For example, ``'GET'``. - - - .. attribute:: path - - Contains the request path. - - - .. attribute:: request_version - - Contains the version string from the request. For example, ``'HTTP/1.0'``. - - - .. attribute:: headers - - Holds an instance of the class specified by the :attr:`MessageClass` class - variable. This instance parses and manages the headers in the HTTP - request. - - - .. attribute:: rfile - - Contains an input stream, positioned at the start of the optional input - data. - - - .. attribute:: 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. - - - :class:`BaseHTTPRequestHandler` has the following class variables: - - - .. attribute:: 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'``. - - - .. attribute:: sys_version - - Contains the Python system version, in a form usable by the - :attr:`version_string` method and the :attr:`server_version` class - variable. For example, ``'Python/1.4'``. - - - .. attribute:: error_message_format - - Specifies a format string for building an error response to the client. It - uses parenthesized, keyed format specifiers, so the format operand must be - a dictionary. The *code* key should be an integer, specifying the numeric - HTTP error code value. *message* should be a string containing a - (detailed) error message of what occurred, and *explain* should be an - explanation of the error code number. Default *message* and *explain* - values can found in the *responses* class variable. - - - .. attribute:: error_content_type - - Specifies the Content-Type HTTP header of error responses sent to the - client. The default value is ``'text/html'``. - - - .. attribute:: 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 :meth:`send_header`) in all of its responses to clients. - For backwards compatibility, the setting defaults to ``'HTTP/1.0'``. - - - .. attribute:: MessageClass - - .. index:: single: Message (in module mimetools) - - Specifies a :class:`rfc822.Message`\ -like class to parse HTTP headers. - Typically, this is not overridden, and it defaults to - :class:`mimetools.Message`. - - - .. attribute:: responses - - This variable 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 (see the - :attr:`error_message_format` class variable). - - - A :class:`BaseHTTPRequestHandler` instance has the following methods: - - - .. method:: handle() - - Calls :meth:`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 :meth:`do_\*` - methods. - - - .. method:: handle_one_request() - - This method will parse and dispatch the request to the appropriate - :meth:`do_\*` method. You should never need to override it. - - - .. method:: send_error(code[, message]) - - Sends and logs a complete error reply to the client. The numeric *code* - specifies the HTTP error code, with *message* as optional, more specific text. A - complete set of headers is sent, followed by text composed using the - :attr:`error_message_format` class variable. - - - .. method:: send_response(code[, message]) - - Sends a response header and logs the accepted request. The HTTP response - line is sent, followed by *Server* and *Date* headers. The values for - these two headers are picked up from the :meth:`version_string` and - :meth:`date_time_string` methods, respectively. - - - .. method:: send_header(keyword, value) - - Writes a specific HTTP header to the output stream. *keyword* should - specify the header keyword, with *value* specifying its value. - - - .. method:: end_headers() - - Sends a blank line, indicating the end of the HTTP headers in the - response. - - - .. method:: 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. - - - .. method:: log_error(...) - - Logs an error when a request cannot be fulfilled. By default, it passes - the message to :meth:`log_message`, so it takes the same arguments - (*format* and additional values). - - - .. method:: 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 - :meth:`log_message` are applied as inputs to the formatting. The client - address and current date and time are prefixed to every message logged. - - - .. method:: version_string() - - Returns the server software's version string. This is a combination of the - :attr:`server_version` and :attr:`sys_version` class variables. - - - .. method:: date_time_string([timestamp]) - - Returns the date and time given by *timestamp* (which must be in the - format returned by :func:`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'``. - - - .. method:: log_date_time_string() - - Returns the current date and time, formatted for logging. - - - .. method:: address_string() - - Returns the client address, formatted for logging. A name lookup is - performed on the client's IP address. - - -.. seealso:: - - Module :mod:`CGIHTTPServer` - Extended request handler that supports CGI scripts. - - Module :mod:`SimpleHTTPServer` - Basic request handler that limits response to files actually under the document - root. - Index: Doc/library/internet.rst =================================================================== --- Doc/library/internet.rst (revisão 62992) +++ Doc/library/internet.rst (cópia de trabalho) @@ -26,7 +26,7 @@ wsgiref.rst urllib.rst urllib2.rst - httplib.rst + http.client.rst ftplib.rst poplib.rst imaplib.rst @@ -40,7 +40,7 @@ basehttpserver.rst simplehttpserver.rst cgihttpserver.rst - cookielib.rst + http.cookiejar.rst cookie.rst xmlrpclib.rst simplexmlrpcserver.rst Index: Doc/library/http.client.rst =================================================================== --- Doc/library/http.client.rst (revisão 62992) +++ Doc/library/http.client.rst (cópia de trabalho) @@ -1,14 +1,14 @@ -:mod:`httplib` --- HTTP protocol client +:mod:`http.client` --- HTTP protocol client ======================================= -.. module:: httplib +.. module:: http.client :synopsis: HTTP and HTTPS protocol client (requires sockets). .. index:: pair: HTTP; protocol - single: HTTP; httplib (standard module) + single: HTTP; http.client (standard module) .. index:: module: urllib @@ -39,10 +39,10 @@ For example, the following calls all create instances that connect to the server at the same host and port:: - >>> h1 = httplib.HTTPConnection('www.cwi.nl') - >>> h2 = httplib.HTTPConnection('www.cwi.nl:80') - >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80) - >>> h3 = httplib.HTTPConnection('www.cwi.nl', 80, timeout=10) + >>> h1 = http.client.HTTPConnection('www.cwi.nl') + >>> h2 = http.client.HTTPConnection('www.cwi.nl:80') + >>> h3 = http.client.HTTPConnection('www.cwi.nl', 80) + >>> h3 = http.client.HTTPConnection('www.cwi.nl', 80, timeout=10) .. class:: HTTPSConnection(host[, port[, key_file[, cert_file[, strict[, timeout]]]]]) @@ -338,7 +338,7 @@ This dictionary maps the HTTP 1.1 status codes to the W3C names. - Example: ``httplib.responses[httplib.NOT_FOUND]`` is ``'Not Found'``. + Example: ``http.client.responses[http.client.NOT_FOUND]`` is ``'Not Found'``. .. _httpconnection-objects: @@ -464,15 +464,15 @@ Reason phrase returned by server. -.. _httplib-examples: +.. _http.client-examples: Examples -------- Here is an example session that uses the ``GET`` method:: - >>> import httplib - >>> conn = httplib.HTTPConnection("www.python.org") + >>> import http.client + >>> conn = http.client.HTTPConnection("www.python.org") >>> conn.request("GET", "/index.html") >>> r1 = conn.getresponse() >>> print(r1.status, r1.reason) @@ -487,11 +487,11 @@ Here is an example session that shows how to ``POST`` requests:: - >>> import httplib, urllib + >>> import http.client, urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> headers = {"Content-type": "application/x-www-form-urlencoded", ... "Accept": "text/plain"} - >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80") + >>> conn = http.client.HTTPConnection("musi-cal.mojam.com:80") >>> conn.request("POST", "/cgi-bin/query", params, headers) >>> response = conn.getresponse() >>> print(response.status, response.reason) Index: Lib/CGIHTTPServer.py =================================================================== --- Lib/CGIHTTPServer.py (revisão 62992) +++ Lib/CGIHTTPServer.py (cópia de trabalho) @@ -1,365 +0,0 @@ -"""CGI-savvy HTTP Server. - -This module builds on SimpleHTTPServer by implementing GET and POST -requests to cgi-bin scripts. - -If the os.fork() function is not present (e.g. on Windows), -os.popen2() is used as a fallback, with slightly altered semantics; if -that function is not present either (e.g. on Macintosh), only Python -scripts are supported, and they are executed by the current process. - -In all cases, the implementation is intentionally naive -- all -requests are executed sychronously. - -SECURITY WARNING: DON'T USE THIS CODE UNLESS YOU ARE INSIDE A FIREWALL --- it may execute arbitrary Python code or external programs. - -Note that status code 200 is sent prior to execution of a CGI script, so -scripts cannot send other status codes such as 302 (redirect). -""" - - -__version__ = "0.4" - -__all__ = ["CGIHTTPRequestHandler"] - -import os -import sys -import urllib -import BaseHTTPServer -import SimpleHTTPServer -import select - - -class CGIHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): - - """Complete HTTP server with GET, HEAD and POST commands. - - GET and HEAD also support running CGI scripts. - - The POST command is *only* implemented for CGI scripts. - - """ - - # Determine platform specifics - have_fork = hasattr(os, 'fork') - have_popen2 = hasattr(os, 'popen2') - have_popen3 = hasattr(os, 'popen3') - - # Make rfile unbuffered -- we need to read one line and then pass - # the rest to a subprocess, so we can't use buffered input. - rbufsize = 0 - - def do_POST(self): - """Serve a POST request. - - This is only implemented for CGI scripts. - - """ - - if self.is_cgi(): - self.run_cgi() - else: - self.send_error(501, "Can only POST to CGI scripts") - - def send_head(self): - """Version of send_head that support CGI scripts""" - if self.is_cgi(): - return self.run_cgi() - else: - return SimpleHTTPServer.SimpleHTTPRequestHandler.send_head(self) - - def is_cgi(self): - """Test whether self.path corresponds to a CGI script. - - Return a tuple (dir, rest) if self.path requires running a - CGI script, None if not. Note that rest begins with a - slash if it is not empty. - - The default implementation tests whether the path - begins with one of the strings in the list - self.cgi_directories (and the next character is a '/' - or the end of the string). - - """ - - path = self.path - - for x in self.cgi_directories: - i = len(x) - if path[:i] == x and (not path[i:] or path[i] == '/'): - self.cgi_info = path[:i], path[i+1:] - return True - return False - - cgi_directories = ['/cgi-bin', '/htbin'] - - def is_executable(self, path): - """Test whether argument path is an executable file.""" - return executable(path) - - def is_python(self, path): - """Test whether argument path is a Python script.""" - head, tail = os.path.splitext(path) - return tail.lower() in (".py", ".pyw") - - def run_cgi(self): - """Execute a CGI script.""" - path = self.path - dir, rest = self.cgi_info - - i = path.find('/', len(dir) + 1) - while i >= 0: - nextdir = path[:i] - nextrest = path[i+1:] - - scriptdir = self.translate_path(nextdir) - if os.path.isdir(scriptdir): - dir, rest = nextdir, nextrest - i = path.find('/', len(dir) + 1) - else: - break - - # find an explicit query string, if present. - i = rest.rfind('?') - if i >= 0: - rest, query = rest[:i], rest[i+1:] - else: - query = '' - - # dissect the part after the directory name into a script name & - # a possible additional path, to be stored in PATH_INFO. - i = rest.find('/') - if i >= 0: - script, rest = rest[:i], rest[i:] - else: - script, rest = rest, '' - - scriptname = dir + '/' + script - scriptfile = self.translate_path(scriptname) - if not os.path.exists(scriptfile): - self.send_error(404, "No such CGI script (%r)" % scriptname) - return - if not os.path.isfile(scriptfile): - self.send_error(403, "CGI script is not a plain file (%r)" % - scriptname) - return - ispy = self.is_python(scriptname) - if not ispy: - if not (self.have_fork or self.have_popen2 or self.have_popen3): - self.send_error(403, "CGI script is not a Python script (%r)" % - scriptname) - return - if not self.is_executable(scriptfile): - self.send_error(403, "CGI script is not executable (%r)" % - scriptname) - return - - # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html - # XXX Much of the following could be prepared ahead of time! - env = {} - env['SERVER_SOFTWARE'] = self.version_string() - env['SERVER_NAME'] = self.server.server_name - env['GATEWAY_INTERFACE'] = 'CGI/1.1' - env['SERVER_PROTOCOL'] = self.protocol_version - env['SERVER_PORT'] = str(self.server.server_port) - env['REQUEST_METHOD'] = self.command - uqrest = urllib.unquote(rest) - env['PATH_INFO'] = uqrest - env['PATH_TRANSLATED'] = self.translate_path(uqrest) - env['SCRIPT_NAME'] = scriptname - if query: -