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 automatically adapt the import.

Source: lib/basehttpserver.py

This module defines two classes for implementing an HTTP server (WEB servers). Typically, this module is not used directly, but it is used as a base class to create a functional Web servers. View the Simplehttpserver and Cgihttpserver modules.

The first class, Httpserver, is a socketserver.tcpserver subclass, so implements the Socketserver.baseserver interface, which creates and listens to HTTP sockets, allocates requests and handles, The code that creates and runs 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 through the processor's server instance variable.

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 process 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 example, for the request method, the method will be SPAM do_SPAM() called without arguments. 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

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

Server

Include server instance

Command

Contains the command (request type), example: ‘GET‘ .

Path

Include Request path

request_version

String containing the HTTP version 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

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

Wfile

Contains the output stream used to reply to a response response to client clients. The appropriate HTTP protocol must be used when writing to the stream.

Basehttprequesthandler has the following class variables:

server_vesion

Specify the server version, and you may overwrite it. The He format is multiple whitespace-separated strings, where each string is of the form Name[/version], example: ‘BaseHTTP/0.2‘ .

sys_version

Contains the Python version, 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, which are specified in the key format, so the format operand must be a dictionary. The code key should be an integer specifying the HTTP error code value. 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, previously, the content type was always‘text/html‘

protocol_version

This specifies the HTTP protocol version for the response, and if set ‘HTTP/1.1‘ , the server will run an HTTP hard connection; Anyway, your server must contain an exact Content-Length header (using Send_header ()) in all the clients 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 contains an error code number and a 2-tuple mapping with short and long information, example: {code:(shrotmessage, longmessage)} . shortmessage is typically used for message key in an error response, andlongmessage is used to interpret (view Error_message_format class variables).

An Basehttprequesthandler instance has the following methods:

handle ()

Summon a handle_one_request () (or, if a hard connection is enabled, multiple calls) to respond to an HTTP request that comes in, you should never need to overwrite it; instead, 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 need to 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, with more specific text. A complete header setting is sent, followed by the Error_message_format class variable to typeset the text.

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, if the response size is valid, it should be used as the 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 parameters (format and additional values).

log_message (format, ...)

Record an arbitrary message to Sys.tederr, which is a typical override to create a custom error message. The format parameter is a standard Printf-style formatted string, in which other parameters Log_message () are used as input formats. The client IP address and the current date and time are prefixed with each information record (message logged).

version_string ()

Returns the server software version, which 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, and if 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 new timestamp parameters.

log_date_time_string ()

Returns the current date and time, in logging format.

address_string ()

Returns the client address, logging format, which performs a name lookup on the client IP address.

More examples

Create a server that does not run continuously 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.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.