Commit c9d1f438 authored by Давид Ли's avatar Давид Ли

lesson 37

parent a16ad841
from request import Request from request import Request
from response import Response
from static_responder import StaticResponder
import socketserver import socketserver
...@@ -8,29 +10,23 @@ class Handler(socketserver.StreamRequestHandler): ...@@ -8,29 +10,23 @@ class Handler(socketserver.StreamRequestHandler):
def handle(self): def handle(self):
request = Request(self.rfile) request = Request(self.rfile)
response = Response(self.wfile)
static_responder = StaticResponder(request, response)
print(request) print(request)
response_body = '<h1>Hello World!</h1>'
response_body_len = len(response_body.encode())
response = (
'HTTP/1.1 200 OK',
'Content-Type: text/html',
f'Content-Length: {response_body_len}',
'Connection: close',
'',
response_body,
)
self.wfile.write('\r\n'.join(response).encode())
if static_responder.file:
static_responder.prepare_response()
# CR - \r else:
# LF - \n response.add_header('Content-Type', 'text/html')
# b'GET / HTTP/1.1\r\nHost: localhost:1026\r\nConnection: keep-alive\r\nsec-ch-ua: "Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"\r\nsec-ch-ua-mobile: ?0\r\nsec-ch-ua-platform: "macOS"\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7\r\nSec-Fetch-Site: none\r\nSec-Fetch-Mode: navigate\r\nSec-Fetch-User: ?1\r\nSec-Fetch-Dest: document\r\nAccept-Encoding: gzip, deflate, br\r\nAccept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n response.add_header('Connection', 'close')
response.set_body('<h1>Hello World!</h1>')
response.send()
ADDRESS = ('localhost', 1026) ADDRESS = ('localhost', 1027)
socketserver.ThreadingTCPServer.allow_reuse_address = True socketserver.ThreadingTCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer(ADDRESS, Handler) as server: with socketserver.ThreadingTCPServer(ADDRESS, Handler) as server:
......
from os import fstat
class Response:
HTTP_OK = 200
HTTP_BAD_REQUEST = 400
HTTP_NOT_FOUND = 404
HTTP_INTERNAL_SERVER_ERROR = 500
MESSAGES = {
HTTP_OK: 'OK',
HTTP_BAD_REQUEST: 'Bad Request',
HTTP_NOT_FOUND: 'Not Found',
HTTP_INTERNAL_SERVER_ERROR: 'Internal Server Error'
}
PROTOCOL = 'HTTP/1.1'
def __init__(self, wfile):
self.wfile = wfile
self.status = self.HTTP_OK
self.headers = {}
self.body = None
self.file_body = None
def add_header(self, name, value):
self.headers[name] = value
def set_body(self, body):
self.body = body.encode()
self.add_header('Content-Length', len(self.body))
def set_file_body(self, file):
self.file_body = file
size = fstat(file.fileno()).st_size
self.add_header('Content-Length', size)
def __get_status_line(self):
message = self.MESSAGES[self.status]
return f'{self.PROTOCOL} {self.status} {message}'
def __get_headers(self):
headers = []
for name, value in self.headers.items():
headers.append(f'{name}: {value}')
return headers
def _write_file_body(self):
while True:
data = self.file_body.read(1024)
if not data:
break
self.wfile.write(data)
def send(self):
status_line = self.__get_status_line()
headers = self.__get_headers()
response_str = '\r\n'.join([status_line] + headers) + '\r\n\r\n'
self.wfile.write(response_str.encode())
if self.body:
self.wfile.write(self.body)
elif self.file_body:
self._write_file_body()
\ No newline at end of file
from glob import glob
import os
class StaticResponder:
def __init__(self, request, response, static_dir='static'):
self.request = request
self.response = response
self.static_dir = static_dir
self.file = None
self._check_file()
# http://localhost:1027/cat.jpg
def _check_file(self):
file_uri = self.request.uri.replace('..', '')
path = './' + self.static_dir + file_uri
files = glob(path)
if len(files) > 0 and os.path.isfile(files[0]):
self.file = files[0]
def prepare_response(self):
file = open(self.file, 'rb')
self.response.set_file_body(file)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment