Movatterモバイル変換


[0]ホーム

URL:


Previous PageUp One LevelNext PagePython Library ReferenceContentsModule IndexIndex
Previous:11.15 SocketServerUp:11. Internet Protocols andNext:11.17 SimpleHTTPServer

11.16BaseHTTPServer -- Basic HTTP server

 

This module defines two classes for implementing HTTP servers(Web servers). Usually, this module isn't used directly, but is usedas a basis for building functioning Web servers. See theSimpleHTTPServer andCGIHTTPServer modules.

The first class,HTTPServer, is aSocketServer.TCPServer subclass. It creates and listens at theHTTP socket, dispatching the requests to a handler. Code to create andrun 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()

classHTTPServer(server_address, RequestHandlerClass)
This class builds on theTCPServer class bystoring the server address as instancevariables namedserver_name andserver_port. Theserver is accessible by the handler, typically through the handler'sserver instance variable.

classBaseHTTPRequestHandler(request, client_address, server)
This class is usedto handle the HTTP requests that arrive at the server. By itself,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 amethod specific to the request type. The method name is constructedfrom the request. For example, for the request method "SPAM", thedo_SPAM() method will be called with no arguments. All ofthe relevant information is stored in instance variables of thehandler. Subclasses should not need to override or extend the__init__() method.

BaseHTTPRequestHandler has the following instance variables:

client_address
Contains a tuple of the form(host,port) referringto the client's address.

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 theMessageClassclass variable. This instance parses and manages the headers inthe HTTP request.

rfile
Contains an input stream, positioned at the start of the optionalinput data.

wfile
Contains the output stream for writing a response back to the client.Proper adherence to the HTTP protocol must be used when writingto this stream.

BaseHTTPRequestHandler has the following class variables:

server_version
Specifies the server software version. You may want to overridethis.The format is multiple whitespace-separated strings,where each string is of the form name[/version].For example,'BaseHTTP/0.2'.

sys_version
Contains the Python system version, in a form usable by 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 theclient. It uses parenthesized, keyed format specifiers, so theformat operand must be a dictionary. Thecode key shouldbe an integer, specifying the numeric HTTP error code value.message should be a string containing a (detailed) errormessage of what occurred, andexplain should be anexplanation of the error code number. Defaultmessageandexplain values can found in theresponsesclass variable.

protocol_version
This specifies the HTTP protocol version used in responses.Typically, this should not be overridden. Defaults to'HTTP/1.0'.

MessageClass
Specifies arfc822.Message-like class to parse HTTPheaders. Typically, this is not overridden, and it defaults tomimetools.Message. 

responses
This variable contains a mapping of error code integers to two-elementtuples containing 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()
Overrides the superclass'handle() method to provide thespecific handler behavior. This method will parse and dispatchthe request to the appropriatedo_*() method.

send_error(code[, message])
Sends and logs a complete error reply to the client. The numericcode specifies the HTTP error code, withmessage asoptional, more specific text. A complete set of headers is sent,followed by text composed using theerror_message_formatclass variable.

send_response(code[, message])
Sends a response header and logs the accepted request. The HTTPresponse line is sent, followed byServer andDateheaders. The values for these two headers are picked up from theversion_string() anddate_time_string() methods,respectively.

send_header(keyword, value)
Writes a specific MIME header to the output stream.keywordshould specify the header keyword, withvalue specifyingits value.

end_headers()
Sends a blank line, indicating the end of the MIME headers inthe response.

log_request([code[, size]])
Logs an accepted (successful) request.code should specifythe numeric HTTP code associated with the response. If a size ofthe response is available, then it should be passed as thesize parameter.

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

log_message(format, ...)
Logs an arbitrary message tosys.stderr. This is typicallyoverridden to create custom error logging mechanisms. Theformat argument is a standard printf-style format string,where the additional arguments tolog_message() are appliedas inputs to the formatting. The client address and current dateand time are prefixed to every message logged.

version_string()
Returns the server software's version string. This is a combinationof theserver_version andsys_version class variables.

date_time_string()
Returns the current date and time, formatted for a message header.

log_data_time_string()
Returns the current date and time, formatted for logging.

address_string()
Returns the client address, formatted for logging. A name lookupis performed on the client's IP address.

See Also:

ModuleCGIHTTPServer:
Extended request handler that supports CGI scripts.

ModuleSimpleHTTPServer:
Basic request handler that limits response to files actually under the document root.


Previous PageUp One LevelNext PagePython Library ReferenceContentsModule IndexIndex
Previous:11.15 SocketServerUp:11. Internet Protocols andNext:11.17 SimpleHTTPServer
Release 2.2.3, documentation updated on 30 May 2003.
SeeAbout this document... for information on suggesting changes.
[8]ページ先頭

©2009-2026 Movatter.jp