1.server.py代码分析
class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
此类是:覆盖父类的方法。处理HTTP请求的 handler处理request
def handle_one_request(self):
处理请求的方法在最后会丢出来一个方法实现针对不同的方法进行处理的
mname = 'do_' + self.command
if not hasattr(self, mname):
self.send_error(501, "Unsupported method (%s)" % `self.command`)
return
method = getattr(self, mname)
method()
这个方法会接收到一个request 请求之后丢给do_post do_get do_header等去处理一下的!
def do_PING(self):
self.path='/'
self.send_error(202) # 'accepted' 发送202信号过去的
def logRequestInfo(self):
# write a request to the access log.
if accesslog.isEnabledFor(logging.INFO):
format='%s - - [%s] "%s" %s %s "%s" "%s"'
useragent=self.headers.getheader('user-agent') or '-'
referer=self.headers.getheader('referer') or '-' #跟踪上一级来自哪里的链接,跟踪用户行为用的。还可以进行防盗链处理的!
size=str(self.content_length) or '-'
args=( self.address_string(), self.log_date_time_string(), self.raw_requestline.strip(), str(self.response_code) or '?', size, referer, useragent )
accesslog.info( format%args )
写日志的方法定义!
如果有来自客户端的请求的话那就将内容写进到日志中去的!
系统的API定义方法如下:
def getServerIP(self):
# return the IP address of the interface the request arrived on
return self.request.getsockname()[0]
返回服务器的IP地址!
def getServerName(self):
if not self.virtualhostport or self.virtualhostport == 80:
return self.virtualhost
else:
return '%s:%d' % (self.virtualhost, self.virtualhostport)
返回服务器名称。如果不是80端口的话就加上端口进来的!
学习人家的API是如何来写的。启发一下学习编程从看代码开始吧!
def address_string(self):
# override the base version that looks up the FQ hostname.
# we just stick with the IP address...
# ...and even take the real IP adress if we are proxied by Apache.
host, port = self.client_address
realhost=self.headers.get("x-forwarded-for") or host
return str(realhost)
返回客户端的IP值。考虑进来代理的出现了!
阅读(1005) | 评论(0) | 转发(0) |