This commit is contained in:
2021-03-27 16:30:53 +01:00
parent fdbd865889
commit 3615c56152
14 changed files with 280 additions and 110 deletions

View File

@@ -17,7 +17,7 @@ class InvalidStatusLine(HTTPException):
class UnsupportedEncoding(HTTPException):
""" Reponse Encoding not support """
""" Encoding not supported """
def __init(self, enc_type, encoding):
self.enc_type = enc_type
@@ -39,12 +39,28 @@ class HTTPServerException(Exception):
self.body = body
class BadRequest(HTTPServerException):
class HTTPServerCloseException(HTTPServerException):
""" When thrown, the connection should be closed """
class BadRequest(HTTPServerCloseException):
""" Malformed HTTP request"""
status_code = 400
message = "Bad Request"
class Forbidden(HTTPServerException):
""" Request not allowed """
status_code = 403
message = "Forbidden"
class NotFound(HTTPServerException):
""" Resource not found """
status_code = 404
message = "Not Found"
class MethodNotAllowed(HTTPServerException):
""" Method is not allowed """
status_code = 405
@@ -54,7 +70,7 @@ class MethodNotAllowed(HTTPServerException):
self.allowed_methods = allowed_methods
class InternalServerError(HTTPServerException):
class InternalServerError(HTTPServerCloseException):
""" Internal Server Error """
status_code = 500
message = "Internal Server Error"
@@ -66,16 +82,10 @@ class NotImplemented(HTTPServerException):
message = "Not Implemented"
class NotFound(HTTPServerException):
""" Resource not found """
status_code = 404
message = "Not Found"
class Forbidden(HTTPServerException):
""" Request not allowed """
status_code = 403
message = "Forbidden"
class HTTPVersionNotSupported(HTTPServerCloseException):
""" The server does not support the major version HTTP used in the request message """
status_code = 505
message = "HTTP Version Not Supported"
class Conflict(HTTPServerException):
@@ -84,10 +94,10 @@ class Conflict(HTTPServerException):
message = "Conflict"
class HTTPVersionNotSupported(HTTPServerException):
""" The server does not support the major version HTTP used in the request message """
status_code = 505
message = "HTTP Version Not Supported"
class NotModified(HTTPServerException):
""" Requested resource was not modified """
status_code = 304
message = "Not Modified"
class InvalidRequestLine(BadRequest):

View File

@@ -26,42 +26,26 @@ class HTTPSocket:
self.file = self.conn.makefile("rb")
def close(self):
"""
Close this socket
"""
self.file.close()
# self.conn.shutdown(socket.SHUT_RDWR)
self.conn.close()
def is_closed(self):
return self.file is None
def reset_request(self):
"""
Close the file handle of this socket and create a new one.
"""
self.file.close()
self.file = self.conn.makefile("rb")
def __do_receive(self):
if self.conn.fileno() == -1:
raise Exception("Connection closed")
result = self.conn.recv(BUFSIZE)
return result
def receive(self):
"""Receive data from the client up to BUFSIZE
"""
count = 0
while True:
count += 1
try:
return self.__do_receive()
except socket.timeout:
logging.debug("Socket receive timed out after %s seconds", TIMEOUT)
if count == 3:
break
logging.debug("Retrying %s", count)
logging.debug("Timed out after waiting %s seconds for response", TIMEOUT * count)
raise TimeoutError("Request timed out")
def read(self, size=BUFSIZE, blocking=True) -> bytes:
"""
Read bytes up to the specified buffer size. This method will block when `blocking` is set to True (Default).
"""
if blocking:
buffer = self.file.read(size)
else:
@@ -72,14 +56,18 @@ class HTTPSocket:
return buffer
def read_line(self):
try:
line = str(self.read_bytes_line(), FORMAT)
except UnicodeDecodeError:
# Expected UTF-8
raise BadRequest()
return line
"""
Read a line decoded as `httpsocket.FORMAT`.
@return: the decoded line
@raise: UnicodeDecodeError
"""
return str(self.read_bytes_line(), FORMAT)
def read_bytes_line(self) -> bytes:
"""
Read a line as bytes.
"""
line = self.file.readline(MAXLINE + 1)
if len(line) > MAXLINE:
raise InvalidResponse("Line too long")

View File

@@ -23,6 +23,7 @@ class ClientMessage(Message):
def __init__(self, version: str, status: int, msg: str, headers: Dict[str, str], raw=None, body: bytes = None):
super().__init__(version, headers, raw, body)
self.status = status
self.msg = msg
class ServerMessage(Message):

View File

@@ -1,6 +1,7 @@
import logging
import os.path
import re
import urllib
from urllib.parse import urlparse, urlsplit
from httplib.exceptions import InvalidStatusLine, InvalidResponse, BadRequest, InvalidRequestLine
@@ -255,6 +256,19 @@ def parse_uri(uri: str):
return host, port, path
def get_uri(url: str):
"""
Returns a valid URI of the specified URL.
"""
parsed = urlsplit(url)
result = f"http://{parsed.netloc}{parsed.path}"
if parsed.query != '':
result = f"{result}?{parsed.query}"
return result
def base_url(uri: str):
parsed = urlsplit(uri)
path = parsed.path.rsplit("/", 1)[0]
@@ -265,3 +279,7 @@ def absolute_url(uri: str, rel_path: str):
parsed = urlsplit(uri)
path = os.path.normpath(os.path.join(parsed.path, rel_path))
return f"{parsed.scheme}://{parsed.hostname}{path}"
def urljoin(base, url):
return urllib.parse.urljoin(base, url)