Movatterモバイル変換


[0]ホーム

URL:


Navigation

21.22.http.server — HTTP servers

Source code:Lib/http/server.py


This module defines classes for implementing HTTP servers (Web servers).

One class,HTTPServer, is asocketserver.TCPServer subclass.It creates and listens at the HTTP socket, dispatching the requests to ahandler. Code to create and run the server looks like this:

defrun(server_class=HTTPServer,handler_class=BaseHTTPRequestHandler):server_address=('',8000)httpd=server_class(server_address,handler_class)httpd.serve_forever()
classhttp.server.HTTPServer(server_address,RequestHandlerClass)

This class builds on theTCPServer class by storingthe server address as instance variables namedserver_name andserver_port. The server is accessible by the handler, typicallythrough the handler’sserver instance variable.

TheHTTPServer must be given aRequestHandlerClass on instantiation,of which this module provides three different variants:

classhttp.server.BaseHTTPRequestHandler(request,client_address,server)

This class is used to handle the HTTP requests that arrive at the server. Byitself, it cannot respond to any actual HTTP requests; it must be subclassedto handle each request method (e.g. GET or POST).BaseHTTPRequestHandler provides a number of class and instancevariables, and methods for use by subclasses.

The handler will parse the request and the headers, then call a methodspecific to the request type. The method name is constructed from therequest. For example, for the request methodSPAM, thedo_SPAM()method will be called with no arguments. All of the relevant information isstored in instance variables of the handler. Subclasses should not need tooverride or extend the__init__() method.

BaseHTTPRequestHandler has the following instance variables:

client_address

Contains a tuple of the form(host,port) referring to the client’saddress.

server

Contains the server instance.

command

Contains the command (request type). For example,'GET'.

path

Contains the request path.

request_version

Contains the version string from the request. For example,'HTTP/1.0'.

headers

Holds an instance of the class specified by theMessageClass classvariable. This instance parses and manages the headers in the HTTPrequest.

rfile

Contains an input stream, positioned at the start of the optional inputdata.

wfile

Contains the output stream for writing a response back to theclient. Proper adherence to the HTTP protocol must be used when writing tothis stream.

BaseHTTPRequestHandler has the following class variables:

server_version

Specifies the server software version. You may want to override this. Theformat is multiple whitespace-separated strings, where each string is ofthe form name[/version]. For example,'BaseHTTP/0.2'.

sys_version

Contains the Python system version, in a form usable by theversion_string method and theserver_version classvariable. For example,'Python/1.4'.

error_message_format

Specifies a format string for building an error response to the client. Ituses parenthesized, keyed format specifiers, so the format operand must bea dictionary. Thecode key should be an integer, specifying the numericHTTP error code value.message should be a string containing a(detailed) error message of what occurred, andexplain should be anexplanation of the error code number. Defaultmessage andexplainvalues can found in theresponses class variable.

error_content_type

Specifies the Content-Type HTTP header of error responses sent to theclient. The default value is'text/html'.

protocol_version

This specifies the HTTP protocol version used in responses. If set to'HTTP/1.1', the server will permit HTTP persistent connections;however, your servermust then include an accurateContent-Lengthheader (usingsend_header()) in all of its responses to clients.For backwards compatibility, the setting defaults to'HTTP/1.0'.

MessageClass

Specifies anemail.message.Message-like class to parse HTTPheaders. Typically, this is not overridden, and it defaults tohttp.client.HTTPMessage.

responses

This variable contains a mapping of error code integers to two-element tuplescontaining a short and long message. For example,{code:(shortmessage,longmessage)}. Theshortmessage is usually used as themessage key in anerror response, andlongmessage as theexplain key (see theerror_message_format class variable).

ABaseHTTPRequestHandler instance has the following methods:

handle()

Callshandle_one_request() once (or, if persistent connections areenabled, multiple times) to handle incoming HTTP requests. You shouldnever need to override it; instead, implement appropriatedo_*()methods.

handle_one_request()

This method will parse and dispatch the request to the appropriatedo_*() method. You should never need to override it.

handle_expect_100()

When a HTTP/1.1 compliant server receives aExpect:100-continuerequest header it responds back with a100Continue followed by200OK headers.This method can be overridden to raise an error if the server does notwant the client to continue. For e.g. server can chose to send417ExpectationFailed as a response header andreturnFalse.

New in version 3.2.

send_error(code,message=None)

Sends and logs a complete error reply to the client. The numericcodespecifies the HTTP error code, withmessage as optional, more specific text. Acomplete set of headers is sent, followed by text composed using theerror_message_format class variable.

send_response(code,message=None)

Adds a response header to the headers buffer and logs the acceptedrequest. The HTTP response line is written to the internal buffer,followed byServer andDate headers. The values for these two headersare picked up from theversion_string() anddate_time_string() methods, respectively. If the server does notintend to send any other headers using thesend_header() method,thensend_response() should be followed by aend_headers()call.

Changed in version 3.3:Headers are stored to an internal buffer andend_headers()needs to be called explicitly.

send_header(keyword,value)

Adds the HTTP header to an internal buffer which will be written to theoutput stream when eitherend_headers() orflush_headers() isinvoked.keyword should specify the header keyword, withvaluespecifying its value. Note that, after the send_header calls are done,end_headers() MUST BE called in order to complete the operation.

Changed in version 3.2:Headers are stored in an internal buffer.

send_response_only(code,message=None)

Sends the reponse header only, used for the purposes when100Continue response is sent by the server to the client. The headers notbuffered and sent directly the output stream.If themessage is notspecified, the HTTP message corresponding the responsecode is sent.

New in version 3.2.

end_headers()

Adds a blank line(indicating the end of the HTTP headers in the response)to the headers buffer and callsflush_headers().

Changed in version 3.2:The buffered headers are written to the output stream.

flush_headers()

Finally send the headers to the output stream and flush the internalheaders buffer.

New in version 3.3.

log_request(code='-',size='-')

Logs an accepted (successful) request.code should specify the numericHTTP code associated with the response. If a size of the response isavailable, then it should be passed as thesize parameter.

log_error(...)

Logs an error when a request cannot be fulfilled. By default, it passesthe message tolog_message(), so it takes the same arguments(format and additional values).

log_message(format,...)

Logs an arbitrary message tosys.stderr. This is typically overriddento create custom error logging mechanisms. Theformat argument is astandard printf-style format string, where the additional arguments tolog_message() are applied as inputs to the formatting. The clientip address and current date and time are prefixed to every message logged.

version_string()

Returns the server software’s version string. This is a combination of theserver_version andsys_version class variables.

date_time_string(timestamp=None)

Returns the date and time given bytimestamp (which must be None or inthe format returned bytime.time()), formatted for a messageheader. Iftimestamp is omitted, it uses the current date and time.

The result looks like'Sun,06Nov199408:49:37GMT'.

log_date_time_string()

Returns the current date and time, formatted for logging.

address_string()

Returns the client address.

Changed in version 3.3:Previously, a name lookup was performed. To avoid name resolutiondelays, it now always returns the IP address.

classhttp.server.SimpleHTTPRequestHandler(request,client_address,server)

This class serves files from the current directory and below, directlymapping the directory structure to HTTP requests.

A lot of the work, such as parsing the request, is done by the base classBaseHTTPRequestHandler. This class implements thedo_GET()anddo_HEAD() functions.

The following are defined as class-level attributes ofSimpleHTTPRequestHandler:

server_version

This will be"SimpleHTTP/"+__version__, where__version__ isdefined at the module level.

extensions_map

A dictionary mapping suffixes into MIME types. The default issignified by an empty string, and is considered to beapplication/octet-stream. The mapping is used case-insensitively,and so should contain only lower-cased keys.

TheSimpleHTTPRequestHandler class defines the following methods:

do_HEAD()

This method serves the'HEAD' request type: it sends the headers itwould send for the equivalentGET request. See thedo_GET()method for a more complete explanation of the possible headers.

do_GET()

The request is mapped to a local file by interpreting the request as apath relative to the current working directory.

If the request was mapped to a directory, the directory is checked for afile namedindex.html orindex.htm (in that order). If found, thefile’s contents are returned; otherwise a directory listing is generatedby calling thelist_directory() method. This method usesos.listdir() to scan the directory, and returns a404 errorresponse if thelistdir() fails.

If the request was mapped to a file, it is opened and the contents arereturned. AnyOSError exception in opening the requested file ismapped to a404,'Filenotfound' error. Otherwise, the contenttype is guessed by calling theguess_type() method, which in turnuses theextensions_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 thecontents of the file are output. If the file’s MIME type starts withtext/ the file is opened in text mode; otherwise binary mode is used.

For example usage, see the implementation of thetest() functioninvocation in thehttp.server module.

TheSimpleHTTPRequestHandler class can be used in the followingmanner in order to create a very basic webserver serving files relative tothe current directory.

importhttp.serverimportsocketserverPORT=8000Handler=http.server.SimpleHTTPRequestHandlerhttpd=socketserver.TCPServer(("",PORT),Handler)print("serving at port",PORT)httpd.serve_forever()

http.server can also be invoked directly using the-mswitch of the interpreter with aportnumber argument. Similar tothe previous example, this serves files relative to the current directory.

python-mhttp.server8000
classhttp.server.CGIHTTPRequestHandler(request,client_address,server)

This class is used to serve either files or output of CGI scripts from thecurrent directory and below. Note that mapping HTTP hierarchic structure tolocal directory structure is exactly as inSimpleHTTPRequestHandler.

Note

CGI scripts run by theCGIHTTPRequestHandler class cannot executeredirects (HTTP code 302), because code 200 (script output follows) issent prior to execution of the CGI script. This pre-empts the statuscode.

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 asdenoting CGI scripts.

Thedo_GET() anddo_HEAD() functions are modified to run CGI scriptsand serve the output, instead of serving files, if the request leads tosomewhere below thecgi_directories path.

TheCGIHTTPRequestHandler defines the following data member:

cgi_directories

This defaults to['/cgi-bin','/htbin'] and describes directories totreat as containing CGI scripts.

TheCGIHTTPRequestHandler defines the following method:

do_POST()

This method serves the'POST' request type, only allowed for CGIscripts. Error 501, “Can only POST to CGI scripts”, is output when tryingto POST to a non-CGI url.

Note that CGI scripts will be run with UID of user nobody, for securityreasons. Problems with the CGI script will be translated to error 403.

CGIHTTPRequestHandler can be enabled in the command line by passingthe--cgi option.:

python-mhttp.server--cgi8000

Previous topic

21.21.socketserver — A framework for network servers

Next topic

21.23.http.cookies — HTTP state management

This Page

Quick search

Enter search terms or a module, class or function name.

Navigation

©Copyright 1990-2017, Python Software Foundation.
The Python Software Foundation is a non-profit corporation.Please donate.
Last updated on Sep 19, 2017.Found a bug?
Created usingSphinx 1.2.

[8]ページ先頭

©2009-2025 Movatter.jp