Python Standard Library BaseHttpServer参数信息

来源:互联网 发布:阿里云pc输入法 编辑:程序博客网 时间:2024/04/30 02:43

BaseHttpServer有一些实例变量,虽然在lib code里有一些说明,但可能不那么清晰,这里我们通过如下的例子进行一些说明:

from BaseHTTPServer import BaseHTTPRequestHandlerimport urlparseclass 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)        returnif __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=GETpath=/real path=/query=request_version=HTTP/1.1SERVER VALUES:server_version=BaseHTTP/0.3sys_version=Python/2.7.5protocol_version=HTTP/1.0HEADERS RECEIVED:accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8accept-encoding=gzip, deflate, sdchaccept-language=en-US,en;q=0.8,zh-CN;q=0.6connection=keep-alivecookie=session=eyJjc3JmX3Rva2VuIjp7IiBiIjoiTXpJM01qQTVaakU0TmpnNE1XSXhZVE5rTUdFNU5UQmxaR1k1Tnprd00yTXpObVZrWmpkaVpnPT0ifX0.BzNF-A.sbFQGhX77G-2hyghsXo49dFFOlEhost=localhost:8080user-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/pythonfrom BaseHTTPServer import BaseHTTPRequestHandler,HTTPServerPORT_NUMBER = 8080#This class will handles any incoming request from the browserclass 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会显示如下信息:



0 0
原创粉丝点击