GrowSystem/classes/http_request.py

73 lines
1.8 KiB
Python

import json
import ure as re
class HttpRequest:
METHOD = {
"GET": "GET",
"POST": "POST"
}
method = ''
path = ''
raw_content = ''
headers = {}
def __init__(self, request):
self.original_request = request
# self.method = method
# self.path = path
# self.headers = headers
# self.raw_content = content
print("http request initialized")
self.parse_request(request)
def parse_request(self, request):
# Split the request into lines
lines = request.decode().split('\r\n')
# Extract method, path, and HTTP version from the first line
self.method, self.path, _ = lines[0].split()
# Parse headers
for line in lines[1:]:
if not line:
break # Empty line indicates end of headers
key, value = line.split(': ', 1)
self.headers[key] = value
# Content is assumed to be in the last line
self.raw_content = lines[-1]
def get_content_json(self):
# Parse the POST request content into a dictionary
parsed_content = {}
pairs = self.raw_content.split('&')
for pair in pairs:
key, value = pair.split('=')
parsed_content[key] = value
# Encode the values in the dictionary
encoded_content = {}
for key, value in parsed_content.items():
encoded_value = re.sub(r'%([0-9A-Fa-f]{2})', lambda m: chr(int(m.group(1), 16)), value)
encoded_content[key] = encoded_value
return encoded_content
def __str__(self):
return {
"method": self.method,
"headers": self.headers,
"content": self.raw_content,
"content_json": self.get_content_json()
}