client: cleanup

This commit is contained in:
2021-03-21 13:10:57 +01:00
parent d8a5765fd8
commit 638576f471
5 changed files with 77 additions and 128 deletions

View File

@@ -1,17 +1,22 @@
import logging
from abc import ABC, abstractmethod
from urllib.parse import urlparse
from client.ResponseHandler import ResponseHandler
from client.httpclient import FORMAT, HTTPClient, InvalidResponse, InvalidStatusLine, UnsupportedEncoding
class Command:
command: str
class AbstractCommand(ABC):
def __init__(self, url: str, port: str):
self.url = url
self.port = port
@property
@abstractmethod
def command(self):
pass
@staticmethod
def create(command: str, url: str, port: str):
if command == "GET":
@@ -56,8 +61,12 @@ class Command:
finally:
client.close()
def _await_response(self, client: HTTPClient):
pass
def _await_response(self, client):
while True:
line = client.read_line()
print(line, end="")
if line in ("\r\n", "\n", ""):
break
def _build_message(self, message: str) -> bytes:
return (message + "\r\n").encode(FORMAT)
@@ -81,35 +90,10 @@ class Command:
return host, path
class HeadCommand(Command):
command = "HEAD"
def _await_response(self, client):
while True:
line = client.read_line()
print(line, end="")
if line in ("\r\n", "\n", ""):
break
class GetCommand(Command):
command = "GET"
def _await_response(self, client):
(version, status, msg) = ResponseHandler.get_status_line(client)
logging.debug("Parsed status-line: version: %s, status: %s", version, status)
headers = ResponseHandler.get_headers(client)
logging.debug("Parsed headers: %r", headers)
handler = ResponseHandler.create(client, headers, status, self.url)
handler.handle()
class PostCommand(HeadCommand):
command = "POST"
class AbstractWithBodyCommand(AbstractCommand, ABC):
def _build_message(self, message: str) -> bytes:
body = input("Enter POST data: ").encode(FORMAT)
body = input(f"Enter {self.command} data: ").encode(FORMAT)
print()
message += "Content-Type: text/plain\r\n"
@@ -122,5 +106,34 @@ class PostCommand(HeadCommand):
return message
class PutCommand(PostCommand):
command = "PUT"
class HeadCommand(AbstractCommand):
@property
def command(self):
return "HEAD"
class GetCommand(AbstractCommand):
@property
def command(self):
return "GET"
def _await_response(self, client):
(version, status, msg) = ResponseHandler.get_status_line(client)
logging.debug("Parsed status-line: version: %s, status: %s", version, status)
headers = ResponseHandler.get_headers(client)
logging.debug("Parsed headers: %r", headers)
handler = ResponseHandler.create(client, headers, status, self.url)
handler.handle()
class PostCommand(AbstractWithBodyCommand):
@property
def command(self):
return "POST"
class PutCommand(AbstractWithBodyCommand):
@property
def command(self):
return "PUT"