Skip to content

Instantly share code, notes, and snippets.

@cunla
Created June 18, 2020 22:28
Show Gist options
  • Save cunla/c074179a587c0d012229ee8cc5c04a8c to your computer and use it in GitHub Desktop.
Save cunla/c074179a587c0d012229ee8cc5c04a8c to your computer and use it in GitHub Desktop.
Parse http raw request to python http request
import requests
CRLF = '\r\n'
DEFAULT_HTTP_VERSION = 'HTTP/1.1'
class RequestParser(object):
def __parse_request_line(self, request_line):
request_parts = request_line.split(' ')
self.method = request_parts[0]
self.url = request_parts[1]
self.protocol = request_parts[2] if len(request_parts) > 2 else DEFAULT_HTTP_VERSION
def __init__(self, req_text):
req_lines = req_text.split(CRLF)
self.__parse_request_line(req_lines[0])
ind = 1
self.headers = dict()
while ind < len(req_lines) and len(req_lines[ind]) > 0:
colon_ind = req_lines[ind].find(':')
header_key = req_lines[ind][:colon_ind]
header_value = req_lines[ind][colon_ind + 1:]
self.headers[header_key] = header_value
ind += 1
ind += 1
self.data = req_lines[ind:] if ind < len(req_lines) else None
self.body = CRLF.join(self.data)
def __str__(self):
headers = CRLF.join(f'{key}: {self.headers[key]}' for key in self.headers)
return f'{self.method} {self.url} {self.protocol}{CRLF}' \
f'{headers}{CRLF}{CRLF}{self.body}'
def to_request(self):
req = requests.Request(method=self.method,
url=self.url,
headers=self.headers,
data=self.data, )
return req
if __name__ == '__main__':
r = RequestParser('''POST https://httpbin.org/post\r
Content-Type: application/json\r
\r
{\r
"id": 999,\r
"value": "content"\r
}''')
print(r)
req = req.to_request()
print(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment