Python Standard library basehttpserver Chinese translation

Source: Internet
Author: User

Python Standard library basehttpserver Chinese translation.


Note: The basehttpserver module has been merged into Http.serverin Python3, and when you convert your resource to Python3, the 2to3 tool will self-adapt the import.

Source code: lib/basehttpserver.py

This module defines two classes for implementing an HTTP server (WEB servers). Typically, this module is not used directly. However, it is used as a base class to create functional Web servers.

View the Simplehttpserver and Cgihttpserver modules.

The first class. Httpserver, is a subclass of Socketserver.tcpserver . Thus implements the Socketserver.baseserver interface, which creates and listens for HTTP sockets. The code for assigning requests and processing, creating and executing 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 basehttpserver. Httpserver (Server_address, Requesthandlerclass)

This class is built on tcpserver by storing server addresses as instance variables named server_name and server_port.
The server can be accessed by the processor. Typically, the server instance variable is passed through the processor.

class basehttpserver. Basehttprequesthandler (Request, client_address, server)

This class is used to handle HTTP requests that arrive at the server, and by itself it cannot respond to any actual HTTP requests.

It must subclass to handle each request method (for example, GET or POST).

Basehttprequesthandler provides a number of class and instance variables. and methods that can be used by subclasses.

The processor parses the request and header information, and then invokes a specific method of the request type.

The method name is constructed from the request.

In the sample, for the request method SPAM . do_SPAM()the method will be called without a number of parameters.

All relevant information is stored in the processor's instance variable. Subclasses should not need to overwrite or extend the __init__ method.

Basehttpserverhandler has the following instance variables:

client_address

Includes a ganso about the structure of the client address (host, port) .

Server

Include server instance

Command

Include command (request type), sample: ‘GET‘ .

Path

Include Request path

request_version

A string that includes the HTTP version number of the request, example: ‘HTTP/1.0‘ .

Headers

Has a class instance specified through the MessageClass variable.

This instance resolves and manages header information for HTTP requests.

Rfile

Includes an input stream stream, placed at the beginning of the input data option.

Wfile

Includes the output stream used to reply to a response response to clientclient. The appropriate HTTP protocol must be used when writing to the stream.

Basehttprequesthandler has the following class variables:

server_vesion

Specifies the server version number. You may write it down. The He format is multiple whitespace-separated strings, where each string is of the form Name[/version], example: ‘BaseHTTP/0.2‘ .

sys_version

Includes the Python version number, which is used by the Version_string method and the Server_version class variable.

Example: ‘Python/1.4‘ .

Error_message_format

Specifies that a formatted string is used to create an error response to the client.

It uses arc brackets. The key format is specified, so the format operand must be a dictionary.

The code key should be an integer. Specifies the HTTP error code value. The message should be a string containing the details of an error message,Explain should be an explanation of the number of error codes. The value of the default message and explain can be found in the responses class variable.

Error_content_type

Specifies the error response of the Content-type HTTP hair sent to the client, which is the default value ‘text/html‘ .

2.6 added, in the past, the content type is always‘text/html‘

protocol_version

This specifies the HTTP protocol version number for the response, assuming the setting ‘HTTP/1.1‘ . The server performs an HTTP hard connection; In any case, your server must include an exact Content-Length header (using Send_header ()) in all of the client it responds to.

For backwards compatibility, the default setting is ‘HTTP/1.0‘ .

MessageClass

Specifies a rfc822. The Message-like class to parse the HTTP header. Typically, this does not overwrite, the default setting is Mimetools. Message.

Responses

This variable includes an error code number and a mapping of 2-tuple ancestors including short and long information, sample: {code:(shrotmessage, longmessage)} .

shortmessage often uses the message key in an error response,longmessage is used to interpret (view Error_message_format class variables).

An Basehttprequesthandler instance has the following methods:

handle ()

Summon once Handle_one_request () (or. Suppose a hard connection is enabled, called multiple times, to respond to an HTTP request coming in. You should never need to overwrite it; Implement the appropriate do_* method.

handle_one_request ()

This method will parse and assign the request to the appropriate do_* method, and you should not overwrite it.

send_error (code[, message])

Send and record a full error reply to the client.

Code specifies an HTTP error code, and themessage is optional and many other specific text.

A complete header setting is sent. The text is then typeset using the Error_message_format class variable.

Send_response (Code[,message])

Send a response header and record the accepted request, the HTTP response line is sent, and then the Server and Data header, the values of these two headers are picked up from the version_string and Dare_time_string methods, respectively.

send_header (keyword, value)

Writes a specified HTTP header to the output stream,Ketword should specify the header keyword, and value specifies its values.

end_headers ()

Sends a blank line, and the surface HTTP header response ends.

log_request ([code[,size]])

Record and accept (successful) requests,code should be specified as HTTP code and response traffic, assuming the response size is valid. Should be a size parameter.

log_error (...)

When a request cannot be performed to record an error, by default, it passes the message to Log_message (), so it obtains the same number of parameters (format and additional values).

log_message (format, ...)

Record a random message to the sys.tederr. This is a typical overwrite to create a custom error message principle. The format parameter is a standard Printf-style formatted string, and the other parameters Log_message () are used as input formats. ClientIP address and current date and time as a prefix for each information record (message logged).

version_string ()

Returns the server software version number. This is a combination of server_version and Sys_version class variables.

date_time_string ([timestamp])

Returns the date and time given by Timestramp (these must be returned through the Time.time () format), formatted with an information header, assuming timestamp is omitted. It will use the current date and time.

The result looks like ‘Sun, 06 Nov 1994 08:49:37 GMT‘ .

2.5 added timestamp parameters.

log_date_time_string ()

Returns the current date and time. Logging format.

address_string ()

Returns the client address. Logging format. Perform a name lookup on the ClientIP address.

Many other examples

Create a server that does not have to be cycled until certain conditions are met.

def run_while_true(server_class=BaseHTTPServer.HTTPServer,                   handler_class=BaseHTTPServer.BaseHTTPRequestHandler):    """    This assumes that keep_running() is a function of no arguments which    is tested initially and after each request.  If its return value    is true, the server continues.    """    server_address = (‘‘8000)    httpd = server_class(server_address, handler_class)    while keep_running():        httpd.handle_request()


Additional:

Module: Cgihttpserver
Supports extended request processing for CGI scripts.

Module: Simplehttpserver
In fact, the root file (document root) restricts the response to the underlying request processing of the files.

Python Standard library basehttpserver Chinese translation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.