update
This commit is contained in:
@@ -4,11 +4,10 @@ import sys
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime
|
||||
from time import mktime
|
||||
from typing import Dict
|
||||
from wsgiref.handlers import format_date_time
|
||||
|
||||
from client.httpclient import FORMAT
|
||||
from httplib.exceptions import NotFound, Conflict, Forbidden
|
||||
from httplib.exceptions import NotFound, Forbidden, NotModified
|
||||
from httplib.message import ServerMessage as Message
|
||||
|
||||
root = os.path.join(os.path.dirname(sys.argv[0]), "public")
|
||||
@@ -21,7 +20,6 @@ status_message = {
|
||||
400: "Bad Request",
|
||||
404: "Not Found",
|
||||
500: "Internal Server Error",
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -40,7 +38,6 @@ def create(message: Message):
|
||||
|
||||
class AbstractCommand(ABC):
|
||||
path: str
|
||||
headers: Dict[str, str]
|
||||
msg: Message
|
||||
|
||||
def __init__(self, message: Message):
|
||||
@@ -52,7 +49,15 @@ class AbstractCommand(ABC):
|
||||
def command(self):
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def _conditional_headers(self):
|
||||
pass
|
||||
|
||||
def _get_date(self):
|
||||
"""
|
||||
Returns a string representation of the current date according to RFC 1123
|
||||
"""
|
||||
now = datetime.now()
|
||||
stamp = mktime(now.timetuple())
|
||||
return format_date_time(stamp)
|
||||
@@ -61,7 +66,12 @@ class AbstractCommand(ABC):
|
||||
def execute(self):
|
||||
pass
|
||||
|
||||
def _build_message(self, status: int, content_type: str, body: bytes):
|
||||
def _build_message(self, status: int, content_type: str, body: bytes, extra_headers=None):
|
||||
|
||||
if extra_headers is None:
|
||||
extra_headers = {}
|
||||
self._process_conditional_headers()
|
||||
|
||||
message = f"HTTP/1.1 {status} {status_message[status]}\r\n"
|
||||
message += self._get_date() + "\r\n"
|
||||
|
||||
@@ -72,15 +82,17 @@ class AbstractCommand(ABC):
|
||||
message += f"Content-Type: {content_type}"
|
||||
if content_type.startswith("text"):
|
||||
message += "; charset=UTF-8"
|
||||
message += "\r\n"
|
||||
message += "\r\n"
|
||||
elif content_length > 0:
|
||||
message += f"Content-Type: application/octet-stream"
|
||||
message += f"Content-Type: application/octet-stream\r\n"
|
||||
|
||||
for header in extra_headers:
|
||||
message += f"{header}: {extra_headers[header]}\r\n"
|
||||
|
||||
message += "\r\n"
|
||||
message = message.encode(FORMAT)
|
||||
if content_length > 0:
|
||||
message += body
|
||||
message += b"\r\n"
|
||||
|
||||
return message
|
||||
|
||||
@@ -97,6 +109,30 @@ class AbstractCommand(ABC):
|
||||
|
||||
return path
|
||||
|
||||
def _process_conditional_headers(self):
|
||||
|
||||
for header in self._conditional_headers:
|
||||
tmp = self.msg.headers.get(header)
|
||||
|
||||
if not tmp:
|
||||
continue
|
||||
self._conditional_headers[header]()
|
||||
|
||||
def _if_modified_since(self):
|
||||
date_val = self.msg.headers.get("if-modified-since")
|
||||
if not date_val:
|
||||
return True
|
||||
modified = datetime.utcfromtimestamp(os.path.getmtime(self._get_path(False)))
|
||||
try:
|
||||
min_date = datetime.strptime(date_val, '%a, %d %b %Y %H:%M:%S GMT')
|
||||
except ValueError:
|
||||
return True
|
||||
|
||||
if modified <= min_date:
|
||||
raise NotModified()
|
||||
|
||||
return True
|
||||
|
||||
|
||||
class AbstractModifyCommand(AbstractCommand, ABC):
|
||||
|
||||
@@ -105,6 +141,10 @@ class AbstractModifyCommand(AbstractCommand, ABC):
|
||||
def _file_mode(self):
|
||||
pass
|
||||
|
||||
@property
|
||||
def _conditional_headers(self):
|
||||
return {}
|
||||
|
||||
def execute(self):
|
||||
path = self._get_path(False)
|
||||
dir = os.path.dirname(path)
|
||||
@@ -114,31 +154,47 @@ class AbstractModifyCommand(AbstractCommand, ABC):
|
||||
if os.path.exists(dir) and not os.path.isdir(dir):
|
||||
raise Forbidden("Target directory is an existing file!")
|
||||
|
||||
exists = os.path.exists(path)
|
||||
|
||||
try:
|
||||
with open(path, mode=f"{self._file_mode}b") as file:
|
||||
file.write(self.msg.body)
|
||||
except IsADirectoryError:
|
||||
raise Forbidden("The target resource is a directory!")
|
||||
|
||||
if exists:
|
||||
status = 204
|
||||
else:
|
||||
status = 201
|
||||
|
||||
return self._build_message(status, None, )
|
||||
|
||||
|
||||
class HeadCommand(AbstractCommand):
|
||||
@property
|
||||
def command(self):
|
||||
return "HEAD"
|
||||
|
||||
@property
|
||||
def _conditional_headers(self):
|
||||
return {'if-modified-since': self._if_modified_since}
|
||||
|
||||
def execute(self):
|
||||
path = self._get_path()
|
||||
|
||||
mime = mimetypes.guess_type(path)[0]
|
||||
return self._build_message(200, mime, b"")
|
||||
|
||||
@property
|
||||
def command(self):
|
||||
return "HEAD"
|
||||
|
||||
|
||||
class GetCommand(AbstractCommand):
|
||||
@property
|
||||
def command(self):
|
||||
return "GET"
|
||||
|
||||
@property
|
||||
def _conditional_headers(self):
|
||||
return {'if-modified-since': self._if_modified_since}
|
||||
|
||||
def get_mimetype(self, path):
|
||||
mime = mimetypes.guess_type(path)[0]
|
||||
|
||||
|
Reference in New Issue
Block a user