mirror of
https://github.com/python/cpython.git
synced 2025-12-15 21:44:50 +00:00
Create http package. #2883.
This commit is contained in:
parent
744c2cd325
commit
2442015af2
50 changed files with 930 additions and 1203 deletions
|
|
@ -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 <moshez@zadka.site.co.il>
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
|
@ -1159,8 +1159,8 @@ convert between Unicode and the ACE. Furthermore, the :mod:`socket` module
|
|||
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
|
||||
|
|
|
|||
|
|
@ -1,14 +1,13 @@
|
|||
:mod:`http.client` --- HTTP protocol client
|
||||
===========================================
|
||||
|
||||
:mod:`httplib` --- 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 +38,10 @@ The module provides the following classes:
|
|||
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 +337,7 @@ and also the following constants for integer status codes:
|
|||
|
||||
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 +463,13 @@ HTTPResponse Objects
|
|||
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")
|
||||
>>> 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 +484,11 @@ Here is an example session that uses the ``GET`` method::
|
|||
|
||||
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)
|
||||
|
|
@ -1,14 +1,13 @@
|
|||
:mod:`http.cookiejar` --- Cookie handling for HTTP clients
|
||||
==========================================================
|
||||
|
||||
:mod:`cookielib` --- Cookie handling for HTTP clients
|
||||
=====================================================
|
||||
|
||||
.. module:: cookielib
|
||||
.. module:: http.cookiejar
|
||||
:synopsis: Classes for automatic handling of HTTP cookies.
|
||||
.. moduleauthor:: John J. Lee <jjl@pobox.com>
|
||||
.. sectionauthor:: John J. Lee <jjl@pobox.com>
|
||||
|
||||
|
||||
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 +17,7 @@ Both the regular Netscape cookie protocol and the protocol defined by
|
|||
: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.
|
||||
|
|
@ -94,7 +93,7 @@ The following classes are provided:
|
|||
.. 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.
|
||||
|
||||
|
|
@ -104,9 +103,10 @@ The following classes are provided:
|
|||
Module :mod:`urllib2`
|
||||
URL opening with automatic cookie handling.
|
||||
|
||||
Module :mod:`Cookie`
|
||||
Module :mod:`http.cookies`
|
||||
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:`http.cookies` modules do not depend on each
|
||||
other.
|
||||
|
||||
http://wwwsearch.sf.net/ClientCookie/
|
||||
Extensions to this module, including a class for reading Microsoft Internet
|
||||
|
|
@ -115,7 +115,7 @@ The following classes are provided:
|
|||
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
|
||||
|
|
@ -339,7 +339,7 @@ methods:
|
|||
|
||||
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:`Cookie` instance. *request* is an object
|
||||
implementing the interface defined by the documentation for
|
||||
:meth:`CookieJar.extract_cookies`.
|
||||
|
||||
|
|
@ -348,7 +348,7 @@ methods:
|
|||
|
||||
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:`Cookie` instance. *request* is an object
|
||||
implementing the interface defined by the documentation for
|
||||
:meth:`CookieJar.add_cookie_header`.
|
||||
|
||||
|
|
@ -424,10 +424,10 @@ 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):
|
||||
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
|
||||
|
|
@ -584,8 +584,6 @@ combinations of the above flags:
|
|||
Equivalent to ``DomainStrictNoDots|DomainStrictNonDomain``.
|
||||
|
||||
|
||||
.. _cookielib-cookie-objects:
|
||||
|
||||
Cookie Objects
|
||||
--------------
|
||||
|
||||
|
|
@ -594,7 +592,7 @@ 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)
|
||||
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
|
||||
|
|
@ -606,7 +604,7 @@ internal consistency, so you should know what you're doing if you do that.
|
|||
|
||||
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.
|
||||
|
||||
|
||||
|
|
@ -664,7 +662,7 @@ internal consistency, so you should know what you're doing if you do that.
|
|||
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.
|
||||
|
||||
|
||||
|
|
@ -713,23 +711,21 @@ The :class:`Cookie` class also defines the following method:
|
|||
cookie has expired at the specified time.
|
||||
|
||||
|
||||
.. _cookielib-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/")
|
||||
|
|
@ -740,7 +736,7 @@ Netscape cookies, and block some domains from setting cookies or having them
|
|||
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"])
|
||||
|
|
@ -1,14 +1,13 @@
|
|||
:mod:`http.cookies` --- HTTP state management
|
||||
=============================================
|
||||
|
||||
:mod:`Cookie` --- HTTP state management
|
||||
=======================================
|
||||
|
||||
.. module:: Cookie
|
||||
.. module:: http.cookies
|
||||
:synopsis: Support for HTTP state management (cookies).
|
||||
.. moduleauthor:: Timothy O'Malley <timo@alum.mit.edu>
|
||||
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
|
||||
|
||||
|
||||
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 +62,7 @@ result, the parsing rules used are a bit less strict.
|
|||
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,9 +71,9 @@ your applications, for the same reason why you should not use the
|
|||
|
||||
.. seealso::
|
||||
|
||||
Module :mod:`cookielib`
|
||||
HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie`
|
||||
modules do not depend on each other.
|
||||
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
|
||||
This is the state management specification implemented by this module.
|
||||
|
|
@ -206,15 +205,15 @@ Morsel Objects
|
|||
Example
|
||||
-------
|
||||
|
||||
The following example demonstrates how to use the :mod:`Cookie` module.
|
||||
The following example demonstrates how to use the :mod:`http.cookies` module.
|
||||
|
||||
.. doctest::
|
||||
:options: +NORMALIZE_WHITESPACE
|
||||
|
||||
>>> import Cookie
|
||||
>>> C = Cookie.SimpleCookie()
|
||||
>>> C = Cookie.SerialCookie()
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> from http import cookies
|
||||
>>> C = cookies.SimpleCookie()
|
||||
>>> C = cookies.SerialCookie()
|
||||
>>> C = cookies.SmartCookie()
|
||||
>>> C["fig"] = "newton"
|
||||
>>> C["sugar"] = "wafer"
|
||||
>>> print(C) # generate HTTP headers
|
||||
|
|
@ -223,32 +222,32 @@ The following example demonstrates how to use the :mod:`Cookie` module.
|
|||
>>> print(C.output()) # same thing
|
||||
Set-Cookie: fig=newton
|
||||
Set-Cookie: sugar=wafer
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C = 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 = 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 = 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 = cookies.SmartCookie()
|
||||
>>> C["oreo"] = "doublestuff"
|
||||
>>> C["oreo"]["path"] = "/"
|
||||
>>> print(C)
|
||||
Set-Cookie: oreo=doublestuff; Path=/
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C = cookies.SmartCookie()
|
||||
>>> C["twix"] = "none for you"
|
||||
>>> C["twix"].value
|
||||
'none for you'
|
||||
>>> C = Cookie.SimpleCookie()
|
||||
>>> C = cookies.SimpleCookie()
|
||||
>>> C["number"] = 7 # equivalent to C["number"] = str(7)
|
||||
>>> C["string"] = "seven"
|
||||
>>> C["number"].value
|
||||
|
|
@ -258,7 +257,7 @@ The following example demonstrates how to use the :mod:`Cookie` module.
|
|||
>>> print(C)
|
||||
Set-Cookie: number=7
|
||||
Set-Cookie: string=seven
|
||||
>>> C = Cookie.SerialCookie()
|
||||
>>> C = cookies.SerialCookie()
|
||||
>>> C["number"] = 7
|
||||
>>> C["string"] = "seven"
|
||||
>>> C["number"].value
|
||||
|
|
@ -268,7 +267,7 @@ The following example demonstrates how to use the :mod:`Cookie` module.
|
|||
>>> print(C)
|
||||
Set-Cookie: number="I7\012."
|
||||
Set-Cookie: string="S'seven'\012p1\012."
|
||||
>>> C = Cookie.SmartCookie()
|
||||
>>> C = cookies.SmartCookie()
|
||||
>>> C["number"] = 7
|
||||
>>> C["string"] = "seven"
|
||||
>>> C["number"].value
|
||||
|
|
@ -1,9 +1,8 @@
|
|||
:mod:`http.server` --- HTTP servers
|
||||
===================================
|
||||
|
||||
:mod:`BaseHTTPServer` --- Basic HTTP server
|
||||
===========================================
|
||||
|
||||
.. module:: BaseHTTPServer
|
||||
:synopsis: Basic HTTP server (base class for SimpleHTTPServer and CGIHTTPServer).
|
||||
.. module:: http.server
|
||||
:synopsis: HTTP server and request handlers.
|
||||
|
||||
|
||||
.. index::
|
||||
|
|
@ -12,21 +11,13 @@
|
|||
single: URL
|
||||
single: httpd
|
||||
|
||||
.. index::
|
||||
module: SimpleHTTPServer
|
||||
module: CGIHTTPServer
|
||||
This module defines classes for implementing HTTP servers (Web servers).
|
||||
|
||||
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.
|
||||
One 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::
|
||||
|
||||
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):
|
||||
def run(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
|
||||
server_address = ('', 8000)
|
||||
httpd = server_class(server_address, handler_class)
|
||||
httpd.serve_forever()
|
||||
|
|
@ -40,13 +31,16 @@ to a handler. Code to create and run the server looks like this::
|
|||
through the handler's :attr:`server` instance variable.
|
||||
|
||||
|
||||
The :class:`HTTPServer` must be given a *RequestHandlerClass* on instantiation,
|
||||
of which this module provides three different variants:
|
||||
|
||||
.. class:: BaseHTTPRequestHandler(request, client_address, server)
|
||||
|
||||
This class is used to handle the HTTP requests that arrive at the server. By
|
||||
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.
|
||||
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
|
||||
|
|
@ -57,65 +51,54 @@ to a handler. Code to create and run the server looks like this::
|
|||
|
||||
: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
|
||||
|
|
@ -126,13 +109,11 @@ to a handler. Code to create and run the server looks like this::
|
|||
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
|
||||
|
|
@ -141,7 +122,6 @@ to a handler. Code to create and run the server looks like this::
|
|||
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)
|
||||
|
|
@ -150,7 +130,6 @@ to a handler. Code to create and run the server looks like this::
|
|||
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
|
||||
|
|
@ -159,10 +138,8 @@ to a handler. Code to create and run the server looks like this::
|
|||
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
|
||||
|
|
@ -170,13 +147,11 @@ to a handler. Code to create and run the server looks like this::
|
|||
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*
|
||||
|
|
@ -184,7 +159,6 @@ to a handler. Code to create and run the server looks like this::
|
|||
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
|
||||
|
|
@ -192,26 +166,22 @@ to a handler. Code to create and run the server looks like this::
|
|||
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
|
||||
|
|
@ -227,13 +197,11 @@ to a handler. Code to create and run the server looks like this::
|
|||
: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
|
||||
|
|
@ -242,24 +210,113 @@ to a handler. Code to create and run the server looks like this::
|
|||
|
||||
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::
|
||||
.. class:: SimpleHTTPRequestHandler(request, client_address, server)
|
||||
|
||||
Module :mod:`CGIHTTPServer`
|
||||
Extended request handler that supports CGI scripts.
|
||||
This class serves files from the current directory and below, directly
|
||||
mapping the directory structure to HTTP requests.
|
||||
|
||||
Module :mod:`SimpleHTTPServer`
|
||||
Basic request handler that limits response to files actually under the document
|
||||
root.
|
||||
A lot of the work, such as parsing the request, is done by the base class
|
||||
:class:`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.
|
||||
|
||||
|
||||
.. 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`.
|
||||
|
||||
.. 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 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 method:
|
||||
|
||||
.. 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.
|
||||
|
|
@ -26,7 +26,7 @@ is currently supported on most popular platforms. Here is an overview:
|
|||
wsgiref.rst
|
||||
urllib.rst
|
||||
urllib2.rst
|
||||
httplib.rst
|
||||
http.client.rst
|
||||
ftplib.rst
|
||||
poplib.rst
|
||||
imaplib.rst
|
||||
|
|
@ -37,10 +37,8 @@ is currently supported on most popular platforms. Here is an overview:
|
|||
uuid.rst
|
||||
urlparse.rst
|
||||
socketserver.rst
|
||||
basehttpserver.rst
|
||||
simplehttpserver.rst
|
||||
cgihttpserver.rst
|
||||
cookielib.rst
|
||||
cookie.rst
|
||||
http.server.rst
|
||||
http.cookies.rst
|
||||
http.cookiejar.rst
|
||||
xmlrpc.client.rst
|
||||
xmlrpc.server.rst
|
||||
|
|
|
|||
|
|
@ -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 <moshez@zadka.site.co.il>
|
||||
|
||||
|
||||
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.
|
||||
|
||||
|
|
@ -489,7 +489,7 @@ sends some bytes, and reads part of the response::
|
|||
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""")
|
||||
|
||||
|
|
|
|||
|
|
@ -37,7 +37,7 @@ The :mod:`urllib2` module defines the following functions:
|
|||
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 <http://www.cs.tut.fi/~jkorpela/http.html>`_)
|
||||
|
||||
Raises :exc:`URLError` on errors.
|
||||
|
|
@ -100,7 +100,7 @@ The following exceptions are raised as appropriate:
|
|||
|
||||
An HTTP status code as defined in `RFC 2616 <http://www.faqs.org/rfcs/rfc2616.html>`_.
|
||||
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`.
|
||||
|
||||
|
||||
|
||||
|
|
@ -133,10 +133,11 @@ The following classes are provided:
|
|||
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
|
||||
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.
|
||||
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.
|
||||
|
||||
*unverifiable* should indicate whether the request is unverifiable, as defined
|
||||
by RFC 2965. It defaults to False. An unverifiable request is one whose URL
|
||||
|
|
@ -627,7 +628,7 @@ HTTPCookieProcessor Objects
|
|||
|
||||
.. attribute:: HTTPCookieProcessor.cookiejar
|
||||
|
||||
The :class:`cookielib.CookieJar` in which cookies are stored.
|
||||
The :class:`http.cookiejar.CookieJar` in which cookies are stored.
|
||||
|
||||
|
||||
.. _proxy-handler:
|
||||
|
|
|
|||
|
|
@ -260,7 +260,7 @@ manipulation of WSGI response headers using a mapping-like interface.
|
|||
: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 @@ request. (E.g., using the :func:`shift_path_info` function from
|
|||
|
||||
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:
|
||||
|
||||
|
|
|
|||
|
|
@ -506,14 +506,14 @@ transport. The following example shows how:
|
|||
|
||||
::
|
||||
|
||||
import xmlrpc.client, httplib
|
||||
import xmlrpc.client, http.client
|
||||
|
||||
class ProxiedTransport(xmlrpc.client.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))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue