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

lesson 35

parents
__pycache__/*
\ No newline at end of file
from request import Request
import socketserver
class Handler(socketserver.StreamRequestHandler):
# self.request - client socket
def handle(self):
request = Request(self.rfile)
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())
# CR - \r
# LF - \n
# 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
ADDRESS = ('localhost', 1026)
socketserver.ThreadingTCPServer.allow_reuse_address = True
with socketserver.ThreadingTCPServer(ADDRESS, Handler) as server:
server.serve_forever()
class Request:
def __init__(self, rfile):
self.file = rfile
self.method = None
self.uri = None
self.protocol = None
self.headers = {}
self.body = None
self.__parse_request_line()
self.__parse_headers()
self.__parse_body()
def __parse_request_line(self):
request_line = self.__readline()
# GET / HTTP/1.1 ['GET', '/', 'HTTP/1.1']
self.method, self.uri, self.protocol = request_line.split()
def __readline(self):
return self.file.readline().decode().strip()
def __parse_headers(self):
while True:
header = self.__readline()
if header == '':
break
name, value = header.split(': ')
self.headers[name] = value
def __parse_body(self):
if 'Content-Length' in self.headers:
content_length = int(self.headers['Content-Length'])
self.body = self.file.read(content_length)
def __str__(self):
return (
f'{"-" * 30}\n'
f'{self.method} {self.uri}'
)
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