BaseHttpServer有一些实例变量,虽然在lib code里有一些说明,但可能不那么清晰,这里我们通过如下的例子进行一些说明:
from BaseHTTPServer import BaseHTTPRequestHandler
import urlparse
class GetHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse.urlparse(self.path)
message_parts = [
'CLIENT VALUES:',
'client_address=%s (%s)' % (self.client_address,
self.address_string()),
'command=%s' % self.command,
'path=%s' % self.path,
'real path=%s' % parsed_path.path,
'query=%s' % parsed_path.query,
'request_version=%s' % self.request_version,
'',
'SERVER VALUES:',
'server_version=%s' % self.server_version,
'sys_version=%s' % self.sys_version,
'protocol_version=%s' % self.protocol_version,
'',
'HEADERS RECEIVED:',
]
for name, value in sorted(self.headers.items()):
message_parts.append('%s=%s' % (name, value.rstrip()))
message_parts.append('')
message = '\r\n'.join(message_parts)
self.send_response(200)
self.end_headers()
self.wfile.write(message)
return
if __name__ == '__main__':
from BaseHTTPServer import HTTPServer
server = HTTPServer(('localhost', 8080), GetHandler)
print 'Starting server, use <Ctrl-C> to stop'
server.serve_forever()
通过Chrome浏览器访问localhost:8080,网页上会显示如下信息:
CLIENT VALUES: client_address=('127.0.0.1', 63180) (xxxxxxx) command=GET path=/ real path=/ query= request_version=HTTP/1.1 SERVER VALUES: server_version=BaseHTTP/0.3 sys_version=Python/2.7.5 protocol_version=HTTP/1.0 HEADERS RECEIVED: accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 accept-encoding=gzip, deflate, sdch accept-language=en-US,en;q=0.8,zh-CN;q=0.6 connection=keep-alive cookie=session=eyJjc3JmX3Rva2VuIjp7IiBiIjoiTXpJM01qQTVaakU0TmpnNE1XSXhZVE5rTUdFNU5UQmxaR1k1Tnprd00yTXpObVZrWmpkaVpnPT0ifX0.BzNF-A.sbFQGhX77G-2hyghsXo49dFFOlE host=localhost:8080 user-agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36
对比HTTP Request Header的信息部分:
[method] [URL] [version]
[headers]
[body]
从信息中可以看到这些变量的意义:
self.client_address:包括ip地址和端口号的一个tuple。
self.command:HTTP request [method]
self.path:[URL]
self.request_version:[version]
当然还有一些这个脚本中并未涉及到,但是有可能有关系的变量:
self.connection:客户端连接的socket实例,可以通过self.connection.send()向客户端返回一些数据。例子如下:
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
PORT_NUMBER = 8080
#This class will handles any incoming request from the browser
class myHandler(BaseHTTPRequestHandler):
#Handler for the GET requests
def do_GET(self):
print "self.path: " + self.path
'''
self.path shows the wanted url path.
It should be the path after "GET" in the http request header
'''
if self.connection:
print "self.connection: %s" % self.connection
print "dir(self.connection): %s" % dir(self.connection)
self.connection.send("Hello Connection!")
'''
self.connection is the socket connection between this server and
the client.
After the test, the "Hello Connection!" is shown in the browser when
the connection comes from browser.
'''
else:
print "self.connection is None"
try:
#Create a web server and define the handler to manage the incoming request
server = HTTPServer(('', PORT_NUMBER), myHandler)
print 'Started httpserver on port ' , PORT_NUMBER
print ''
#Wait forever for incoming htto requests
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down the web server'
server.socket.close()
运行之后通过浏览器访问Server,浏览器会显示"Hello Connection!"
Console会显示如下信息: