基于tcp协议,自行处理http报文
class HttpRequest:
'''http请求对象'''
def __init__(self,protocol,data):
self.__protocol = protocol
self.__data = data
def getHeaderParameter(self,parameterKey):
__parameterValue = re.findall(r'%s: (.*)\n'%parameterKey,self.__data)
if __parameterValue:
parameterValue = __parameterValue[0].strip()
else:
parameterValue = None
return parameterValue
def getGetData(self):
getData = None
dataStr = re.findall(r' /\?(.*) HTTP/1.1\r\n',self.__data)
if dataStr:
dataStr = dataStr[0].strip()
dataStrList = re.split("&",dataStr)
getData = {}
for dataItem in dataStrList:
__dataStr = re.split("=",dataItem)
getData[__dataStr[0]] = __dataStr[1]
return getData
def getPostData(self):
postData = None
if self.__data.startswith("POST"):
dataStr = re.findall(r'\r\n(.*)$',self.__data)[0].strip()
dataStrList = re.split("&",dataStr)
postData = {}
for dataItem in dataStrList:
__dataStr = re.split("=",dataItem)
postData[__dataStr[0]] = __dataStr[1]
return postData
def sendHttpResponse(self,body):
response = '''
HTTP/1.1 200 OK\r
Date: %s\r
Server: h5gc\r
Content-Type: text/html;charset=utf-8\r
Content-Length: %d\r\n\r
%s
'''.lstrip() % (
datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'),
len(body),
body
)
self.__protocol.transport.write(response)
self.__protocol.transport.loseConnection()