Esempio n. 1
0
	def __init__(self, conn):
		self.stream = SocketWrapper(conn)
		headers, method, resource, version = self.parse()
		self.headers = HTTPHeaders(headers)
		self.method = method
		self.resource = resource
		self.version = version
Esempio n. 2
0
class HTTPRequest(object):
	def __init__(self, conn):
		self.stream = SocketWrapper(conn)
		headers, method, resource, version = self.parse()
		self.headers = HTTPHeaders(headers)
		self.method = method
		self.resource = resource
		self.version = version
	
	def skip_ws(self):
		while True:
			x = self.stream.read(1)
			if not x.isspace():
				self.stream.seek(-1, 1)
				return

	def get_int(self):
		x = None
		result = ''
		while True:
			x = self.stream.read(1)
			if not x.isdigit():
				self.stream.seek(-1, 1)
				return result
			result += x

	def extract_version(self):
		self.skip_ws()
		http_literal = self.stream.read(4)
		if http_literal != 'HTTP':
			raise ParsingError()
	
		ch = self.stream.read(1)
		if ch != '/':
			raise ParsingError()
		
		major_version = self.get_int()
		ch = self.stream.read(1)
		if ch != '.':
			raise ParsingError()
		minor_version = self.get_int()
		
		return major_version, minor_version

	def parse(self):
		# method
		method = self.stream.read(3)
		if method != 'GET':
			raise NotSupportedMethod()
		
		# resource
		self.skip_ws()
		resource = ''
		while True:
			c = self.stream.read(1)
			if c.isspace():
				break
			resource += c
	
		# version
		version = self.extract_version()
	
		self.skip_ws()
	
		headers = {}
		while True:
			# key
			key = ''
			while True:
				c = self.stream.read(1)
				if c == ':':
					break
				key += c
	
			self.skip_ws()
			value = ''
			while True:
				c = self.stream.read(1)
				if c == '\r':
					c = self.stream.read(1)
					if c == '\n':
						break
				value += c
	
			headers[key] = value
	
			# end of headers
			s = self.stream.read(2)
			if s == '\r\n':
				break
	
			# push the two characters back.
			self.stream.seek(-2, 1)
		return headers, method, resource, version