Python类库中文翻译:BaseHTTPServer — 基本 HTTP 服务器

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 SimpleHTTPServer and CGIHTTPServer modules.
这个模块定义了两个类用来实现 HTTP 服务器(WEB服务器)。通常本模块不会直接使用。

The first class, HTTPServer, is a 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:
第一个类,HTTPServer 是一个 SocketServer.TCPServer 的子集。他创建并监听 HTTP 套接字,分配 requests 到处理器(handler)。编码创建并运行这个服务器看起来像这样:

def run(server_class=BaseHTTPServer.HTTPServer,
handler_class=BaseHTTPServer.BaseHTTPRequestHandler):
server_address = (”, 8000)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()

class HTTPServer( server_address, RequestHandlerClass)
This class builds on the TCPServer class by storing the server address as instance variables named server_name and server_port. The server is accessible by the handler, typically through the handler’s server instance variable.

class BaseHTTPRequestHandler( request, client_address, server)
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). BaseHTTPRequestHandler provides a number of class and instance variables, and methods for use by subclasses.

这个类在 HTTP 请求到达时处理它。实际上它自身并不能对任何 HTTP 请求作出响应,他必须存在派生类用来处理每一个请求方法(例如 GET 或者 POST)。BaseHTTPRequestHandler 为子集提供许多类变量、实例变量和方法。

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 request. For example, for the request method “SPAM”, the do_SPAM() method will be called with no arguments. All of the relevant information is stored in instance variables of the handler. Subclasses should not need to override or extend the __init__() method.
这个处理器将分析请求对象和请求头部,然后根据请求类型调用相应的方法。这个方法名称根据请求类型建立。例子:如果请求方法为’SPAM’,那么 do_SOAM() 方法将无可争议的被调用。所有有关信息被存放在实例变量。派生类应该不需要理睬或扩展 __init() 方法。

BaseHTTPRequestHandler has the following instance variables:
BaseHTTPRequestHandler 拥有下列实例值:

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

command
Contains the command (request type). For example, ‘GET’.
包含命令(请求类型)。例子:’GET’。

path
Contains the request path.
包含请求路径。

request_version
Contains the version string from the request. For example, ‘HTTP/1.0’.
包含请求的版本字符串。例子:’HTTP/1.0′

headers
Holds an instance of the class specified by the MessageClass class variable. This instance parses and manages the headers in the HTTP request.

rfile
Contains an input stream, positioned at the start of the optional input data.
包含输入流,从最初可选的输入数据开始。

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.
包含一个用类写入响应的输出流。请遵守 HTTP 协议在适当的时候使用这个流。

BaseHTTPRequestHandler has the following class variables:
BaseHTTPRequestHandler 拥有下列类属性:

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’.
指定服务器软件版本。你可以不理睬它。

sys_version
Contains the Python system version, in a form usable by the version_string method and the server_version class variable. For example, ‘Python/1.4’.
包含 Python 程序版本,用于 version_string 方法和 server_version 类变量。例子:’Python/1.4’。

error_message_format
Specifies a format string for building an error response to the client. It uses parenthesized, keyed format specifiers, so the format operand must be a dictionary. The code key should be an integer, specifying the numeric HTTP error code value. message should be a string containing a (detailed) error message of what occurred, and explain should be an explanation of the error code number. Default message and explain values can found in the responses class variable.
指定用于发送给客户端的错误回应使用的格式字符串。使用被括号括主的key格式,所以格式化参数必须包含在一个字典里面。code 键是一个整数,为 HTTP 错误代码。message 是一个字符串,为相信的错误消息。explain 是错误代码的说明。默认 message 和 explain 的值可以在responses 类里面找到。

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 server must then include an accurate Content-Length header (using send_header()) in all of its responses to clients. For backwards compatibility, the setting defaults to ‘HTTP/1.0’.
指定HTTP协议版本。如果你设定为’HTTP/1.1’,那么这个服务器支持持久连接。不管什么情况,你的服务器向客户端回应的所有响应(responses)必须包含准确的 Content-Length 头(使用 send_header())。为了向后兼容,默认设置为 ‘HTTP/1.0’ 。

MessageClass
Specifies a rfc822.Message-like class to parse HTTP headers. Typically, this is not overridden, and it defaults to mimetools.Message.

responses
This variable contains a mapping of error code integers to two-element tuples containing a short and long message. For example, {code: (shortmessage, longmessage)}. The shortmessage is usually used as the message key in an error response, and longmessage as the explain key (see the error_message_format class variable).
这个变量包含根据错误代码映射到包含两个长短消息的成员的 tuples 的字典。

A BaseHTTPRequestHandler instance has the following methods:
一个 BaseHTTPRequestHandler 视力拥有下列方法:

handle( )
Calls handle_one_request() once (or, if persistent connections are enabled, multiple times) to handle incoming HTTP requests. You should never need to override it; instead, implement appropriate do_*() methods.
调用 handle_one_request() 一次(如果激活持久连接,则多次)来处理新到达的请求。你应该从来不需要理睬它,而应该使用恰当的 do_*() 方法。

handle_one_request( )
This method will parse and dispatch the request to the appropriate do_*() method. You should never need to override it.
这个处理并分配请求到恰当的 do_*() 方法。你应该从来不需要理睬他。

send_error( code[, message])
Sends and logs a complete error reply to the client. The numeric code specifies the HTTP error code, with message as optional, more specific text. A complete set of headers is sent, followed by text composed using the error_message_format class variable.
为客户端发送一个完整的错误回应并记录它。code 指定了 HTTP 错误代码,可选的 message 提供了更详细的信息。一个完整的响应头被发送后,根据 erroe_message_format 生成的正文被发送。

send_response( code[, message])
Sends a response header and logs the accepted request. The HTTP response line is sent, followed by Server and Date headers. The values for these two headers are picked up from the version_string() and date_time_string() methods, respectively.
发送回应头和记录这个普通请求。HTTP 回应行发送完成后紧跟着发送 Server 和 Date 头。这两个值分别从 version_string() 和 date_time_string() 获得。

send_header( keyword, value)
Writes a specific HTTP header to the output stream. keyword should specify the header keyword, with value specifying its value.
向输出流写入指定的 HTTP 头。keyword 为 HTTP 头键,value 为 HTTP 头的值。

end_headers( )
Sends a blank line, indicating the end of the HTTP headers in the response.
发送一个空白行,标志着回应的 HTTP 头结束。

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.
记录一个成功的普通请求。code 指定为响应的HTTP代码。如果大小是确定的,那么应该传递到 size 参数。

log_error( …)
Logs an error when a request cannot be fulfilled. By default, it passes the message to log_message(), so it takes the same arguments (format and additional values).
记录什么时间的一个请求出错不能执行。默认,它转发消息到 log_message(),它使用一样参数(format 和 附加的参数)。

log_message( format, …)
Logs an arbitrary message to sys.stderr. This is typically overridden to create custom error logging mechanisms. The format argument is a standard printf-style format string, where the additional arguments to log_message() are applied as inputs to the formatting. The client address and current date and time are prefixed to every message logged.
记录任意格式消息到 sys.stderr。它通常被自定义的日子处理程序覆盖。format 参数是标准的 printf-style 格式字符串,由传入 log_message() 的额外参数用于格式化。客户端地址和当前日期和时间被附加在每一个日志消息前面。

version_string( )
Returns the server software’s version string. This is a combination of the server_version and sys_version class variables.
返回服务软件的版本字符串。这是 server_version 和 sys_version 的组合。

date_time_string( [timestamp])
Returns the date and time given by timestamp (which must be in the format returned by time.time()), formatted for a message header. If timestamp is omitted, it uses the current date and time.
根据 timestamp(必须是time.time()返回的格式) 返回时间和日期。如果 timestamp 不存在,那么它将使用当前日期和时间。

The result looks like ‘Sun, 06 Nov 1994 08:49:37 GMT’. New in version 2.5: The timestamp parameter.
他的结果看起来像’Sun, 06 Nov 1994 08:49:37 GMT’。2.5版本的新功能:timestamp 参数。

log_date_time_string( )
Returns the current date and time, formatted for logging.
返回格式化后的用于日志的当前日期和时间。

address_string( )
Returns the client address, formatted for logging. A name lookup is performed on the client’s IP address.
返回格式化后的用于日志的客户地址。对客户IP地址执行名称查询。
译注:真实使用时建议重写本方法为直接输出IP,执行名称查询会严重影响性能。

See Also:
参考:

Module CGIHTTPServer:
Extended request handler that supports CGI scripts.
扩展请求处理器以支持 CGI 脚本。

Module SimpleHTTPServer:
Basic request handler that limits response to files actually under the document root.
基本请求处理器,限制响应的文件范围为 document 目录之下。

译者注:建议继承者设置 rbufsize = 0 来关闭 self.rfile 的缓冲,用来防止少量数据 POST 时不会被 select.select 识别的问题

Comments (1) »

svn 时需要忽略的 python 文件

svn 时需要忽略的 python 文件。
*.pyc *.pyo

其中*.pyc 是被引用时生成的。pyo文件是优化后的代码。

编译成 pyo 就是在控制台执行 python -O -m py_compile file.py

补充:
*.pyd 是 python 的扩展模块,一般是 C 编写(也可能是upx之类的执行码压缩工具生成)。
*.pyw windows专有,使用pythonw 来解释执行。和py的区别是不会显示命令行窗口。标准输出和标准错误输出都是空。标准输入返回EOF。

No comment »

在Python下使用gzip压缩文件

压缩

 

[coolcode lang=”python”]
import gzip
g = gzip.GzipFile(filename=”, mode=’wb’, compresslevel=9, fileobj=open(r’r:\test.log.gz’,’wb’))
g.filename’.gz’
g.write(open(r’r:\test.log’).read())
g.close(
[/coolcode]

filename :为生成的压缩文件 r:\test.log.gz 内包含的文件的名称。如果为空这代表随压缩文件名称变化而变化。
fileobj :生成的压缩文件对象。
g.write(open(r’r:\test.log’).read()):打开被压缩的文件并写入压缩文件。  

解压 

[coolcode lang=”python”]
g = gzip.GzipFile(mode=’rb’, fileobj=open(r’r:\popopo.gz’,’rb’))
open(r’r:\test.log’,’wb’).write(g.read())
[/coolcode]

No comment »