📄 basehttp.py
字号:
"""HTTP server base class.Note: the class in this module doesn't implement any HTTP request; seeSimpleHTTPServer for simple implementations of GET, HEAD and POST(including CGI scripts).Contents:- BaseHTTPRequestHandler: HTTP request handler base class- test: test functionXXX To do:- send server version- log requests even later (to capture byte count)- log user-agent header and other interesting goodies- send error log to separate file- are request names really case sensitive?"""# See also:## HTTP Working Group T. Berners-Lee# INTERNET-DRAFT R. T. Fielding# <draft-ietf-http-v10-spec-00.txt> H. Frystyk Nielsen# Expires September 8, 1995 March 8, 1995## URL: http://www.ics.uci.edu/pub/ietf/http/draft-ietf-http-v10-spec-00.txt# Log files# ---------# # Here's a quote from the NCSA httpd docs about log file format.# # | The logfile format is as follows. Each line consists of: # | # | host rfc931 authuser [DD/Mon/YYYY:hh:mm:ss] "request" ddd bbbb # | # | host: Either the DNS name or the IP number of the remote client # | rfc931: Any information returned by identd for this person,# | - otherwise. # | authuser: If user sent a userid for authentication, the user name,# | - otherwise. # | DD: Day # | Mon: Month (calendar name) # | YYYY: Year # | hh: hour (24-hour format, the machine's timezone) # | mm: minutes # | ss: seconds # | request: The first line of the HTTP request as sent by the client. # | ddd: the status code returned by the server, - if not available. # | bbbb: the total number of bytes sent,# | *not including the HTTP/1.0 header*, - if not available # | # | You can determine the name of the file accessed through request.# # (Actually, the latter is only true if you know the server configuration# at the time the request was made!)__version__ = "0.2"import sysimport timeimport socket # For gethostbyaddr()import stringimport rfc822import mimetoolsimport SocketServer# Default error messageDEFAULT_ERROR_MESSAGE = """\<head><title>Error response</title></head><body><h1>Error response</h1><p>Error code %(code)d.<p>Message: %(message)s.<p>Error code explanation: %(code)s = %(explain)s.</body>"""class HTTPServer(SocketServer.TCPServer): def server_bind(self): """Override server_bind to store the server name.""" SocketServer.TCPServer.server_bind(self) host, port = self.socket.getsockname() if not host or host == '0.0.0.0': host = socket.gethostname() hostname, hostnames, hostaddrs = socket.gethostbyaddr(host) if '.' not in hostname: for host in hostnames: if '.' in host: hostname = host break self.server_name = hostname self.server_port = portclass BaseHTTPRequestHandler(SocketServer.StreamRequestHandler): """HTTP request handler base class. The following explanation of HTTP serves to guide you through the code as well as to expose any misunderstandings I may have about HTTP (so you don't need to read the code to figure out I'm wrong :-). HTTP (HyperText Transfer Protocol) is an extensible protocol on top of a reliable stream transport (e.g. TCP/IP). The protocol recognizes three parts to a request: 1. One line identifying the request type and path 2. An optional set of RFC-822-style headers 3. An optional data part The headers and data are separated by a blank line. The first line of the request has the form <command> <path> <version> where <command> is a (case-sensitive) keyword such as GET or POST, <path> is a string containing path information for the request, and <version> should be the string "HTTP/1.0". <path> is encoded using the URL encoding scheme (using %xx to signify the ASCII character with hex code xx). The protocol is vague about whether lines are separated by LF characters or by CRLF pairs -- for compatibility with the widest range of clients, both should be accepted. Similarly, whitespace in the request line should be treated sensibly (allowing multiple spaces between components and allowing trailing whitespace). Similarly, for output, lines ought to be separated by CRLF pairs but most clients grok LF characters just fine. If the first line of the request has the form <command> <path> (i.e. <version> is left out) then this is assumed to be an HTTP 0.9 request; this form has no optional headers and data part and the reply consists of just the data. The reply form of the HTTP 1.0 protocol again has three parts: 1. One line giving the response code 2. An optional set of RFC-822-style headers 3. The data Again, the headers and data are separated by a blank line. The response code line has the form <version> <responsecode> <responsestring> where <version> is the protocol version (always "HTTP/1.0"), <responsecode> is a 3-digit response code indicating success or failure of the request, and <responsestring> is an optional human-readable string explaining what the response code means. This server parses the request and the headers, and then calls a function specific to the request type (<command>). Specifically, a request SPAM will be handled by a method handle_SPAM(). If no such method exists the server sends an error response to the client. If it exists, it is called with no arguments: do_SPAM() Note that the request name is case sensitive (i.e. SPAM and spam are different requests). The various request details are stored in instance variables: - client_address is the client IP address in the form (host, port); - command, path and version are the broken-down request line; - headers is an instance of mimetools.Message (or a derived class) containing the header information; - rfile is a file object open for reading positioned at the start of the optional input data part; - wfile is a file object open for writing. IT IS IMPORTANT TO ADHERE TO THE PROTOCOL FOR WRITING! The first thing to be written must be the response line. Then follow 0 or more header lines, then a blank line, and then the actual data (if any). The meaning of the header lines depends on the command executed by the server; in most cases, when data is returned, there should be at least one header line of the form Content-type: <type>/<subtype> where <type> and <subtype> should be registered MIME types, e.g. "text/html" or "text/plain". """ # The Python system version, truncated to its first component. sys_version = "Python/" + string.split(sys.version)[0] # 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]. server_version = "BaseHTTP/" + __version__ def handle(self): """Handle a single HTTP request. You normally don't need to override this method; see the class __doc__ string for information on how to handle specific HTTP commands such as GET and POST. """ self.raw_requestline = self.rfile.readline() self.request_version = version = "HTTP/0.9" # Default requestline = self.raw_requestline if requestline[-2:] == '\r\n': requestline = requestline[:-2] elif requestline[-1:] == '\n': requestline = requestline[:-1] self.requestline = requestline words = string.split(requestline) if len(words) == 3: [command, path, version] = words if version[:5] != 'HTTP/': self.send_error(400, "Bad request version (%s)" % `version`) return elif len(words) == 2:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -