Update httpr.py

This commit is contained in:
retoor 2024-12-21 19:49:14 +00:00
parent 2ddfb0c78f
commit 7586a4116b

View File

@ -5,14 +5,13 @@
# The script uses the 'socket' import from Python's standard library. # The script uses the 'socket' import from Python's standard library.
# MIT License: # MIT License:
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import socket import socket
import json import json
@ -85,12 +84,31 @@ class Url:
@property @property
def path(self): def path(self):
return self.url[len(self.schema) + 3 + len(str(self.port)):] or "/" return "/".join(self.url.split("/")[3:]) or "/"
class HTTPResponse: class HTTPResponse:
def __init__(self, headers): def __init__(self, headers):
self.headers = headers self.header_string = headers
self.line, self.headers = self.parse_headers(self.header_string)
self.body = b'' self.body = b''
self.content_length = self.headers.get("Content-Length", 0)
self.transfer_encoding = self.headers.get("Transfer-Encoding", "")
self.connection = self.headers.get("Connection", "")
self.keep_alive = self.connection == "keep-alive"
self.is_chunked = self.transfer_encoding == "chunked"
def __getitem__(self, key):
return self.headers[key]
def parse_headers(self, headers):
header_dict = {}
line, *headers = headers.split(b"\r\n")
for header_line in headers:
key, *value = header_line.split(b": ")
key = key.decode()
value = ": ".join([value.decode() for value in value])
header_dict[key] = int(value) if value.isdigit() else value
return line.decode(), header_dict
@property @property
def json(self): def json(self):
@ -104,7 +122,7 @@ class HTTPResponse:
class HTTPRequest: class HTTPRequest:
def __init__(self, url): def __init__(self, url):
self.url = Url(url) self.url = Url(url)
self.socket = Socket(self.url.host, self.url.port) self.socket = None
self.request_headers = '\r\n'.join([ self.request_headers = '\r\n'.join([
f"GET {self.url.path} HTTP/1.1", f"GET {self.url.path} HTTP/1.1",
f"Host: {self.url.hostname}", f"Host: {self.url.hostname}",
@ -114,24 +132,32 @@ class HTTPRequest:
self.response = None self.response = None
def get(self): def get(self):
self.socket.connect() if not self.socket:
self.socket = Socket(self.url.host, self.url.port)
self.socket.connect()
self.socket.write(self.request_headers) self.socket.write(self.request_headers)
response_headers = self.socket.read_until(b"\r\n\r\n") response_headers = self.socket.read_until(b"\r\n\r\n")
self.response = HTTPResponse(response_headers) self.response = HTTPResponse(response_headers)
data = b'' data = b''
while True: if self.response.is_chunked:
length = self.socket.read_until(b"\r\n") while True:
length = int(length, 16) length = self.socket.read_until(b"\r\n")
chunk = self.socket.read(length + 2, exactly=True) length = int(length, 16)
if isinstance(chunk, bytes): chunk = self.socket.read(length + 2, exactly=True)
data += chunk if isinstance(chunk, bytes):
else: data += chunk
break else:
if chunk == b'\r\n': break
break if chunk == b'\r\n':
self.socket.close() break
elif self.response.content_length:
data = self.socket.read(self.response.content_length)
if not self.response.keep_alive:
self.socket.close()
self.socket = None
self.response.body = data self.response.body = data
return self.response return self.response
http = HTTPRequest("http://localhost:8082/") if __name__ == '__main__':
print(http.get()) http = HTTPRequest("http://localhost:8082/")
print(http.get())