Commit 7aa9af7c authored by ='s avatar =

init template

parents
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9 (homeworks)" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/webinars.iml" filepath="$PROJECT_DIR$/.idea/webinars.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/ap4-instagram" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
from glob import glob
import os
class StaticResponder:
def __init__(self, request, response, static_dir):
self.request = request
self.response = response
self.static_dir = static_dir
self.file = None
self._check_file()
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):
if self.file:
file = open(self.file, "rb")
self.response.set_file_body(file)
class Request:
def __init__(self, file):
self.file = file
self.method = ""
self.uri = ""
self.protocol = ""
self.body = ""
self.headers = {}
self.parse_request_line()
self.parse_headers()
self.parse_body()
def read_line(self):
return self.file.readline().decode().strip()
def parse_request_line(self):
request_line = self.read_line()
try:
self.method, self.uri, self.protocol = request_line.split(" ")
except ValueError as e:
print(e)
if self.protocol != "HTTP/1.1":
raise ValueError("Wrong protocol")
def parse_headers(self):
while True:
header = self.read_line()
if header == "":
break
header_key, header_value = header.split(": ")
self.headers[header_key] = header_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)
\ No newline at end of file
from os import fstat
class Response:
HTTP_OK = 200
HTTP_BAD_REQUEST = 400
HTTP_NOT_FOUND = 404
HTTP_INTERNAL_SERVER_ERROR = 500
HTTP_REDIRECT_STATUS = 303
MESSAGES = {
HTTP_OK: "OK",
HTTP_BAD_REQUEST: "Bad Request",
HTTP_NOT_FOUND: "Not Found",
HTTP_INTERNAL_SERVER_ERROR: "Internal Server Error",
HTTP_REDIRECT_STATUS: "Redirect"
}
PROTOCOL = "HTTP/1.1"
def __init__(self, file):
self.file = file
self.status = self.HTTP_OK
self.headers = []
self.body = None
self.file_body = None
def set_status(self, status):
self.status = status
def _get_status_line(self):
message = self.MESSAGES[self.status]
return f"{self.PROTOCOL} {self.status} {message}"
def _get_headers(self):
status_line = self._get_status_line()
headers = [status_line]
for header in self.headers:
headers.append(f"{header['name']}: {header['value']}")
headers_str = "\r\n".join(headers)
headers_str += "\r\n\r\n"
return headers_str.encode()
def set_body(self, body):
self.body = body.encode()
self.add_header("Content-Length", len(self.body))
def send(self):
self.file.write(self._get_headers())
if self.body:
self.file.write(self.body)
if self.file_body:
self._write_file_body()
def add_header(self, name, value):
self.headers.append({"name": name, "value": value})
def set_file_body(self, file):
self.file_body = file
size = fstat(file.fileno()).st_size
self.add_header("Content-Length", size)
def _write_file_body(self):
while True:
data = self.file_body.read(1024)
if not data:
break
self.file.write(data)
from socketserver import StreamRequestHandler, TCPServer, ThreadingMixIn
from request import Request
from response import Response
from StaticResponder import StaticResponder
class HelloTCPServer(StreamRequestHandler):
def handle(self):
request = Request(self.rfile)
response = Response(self.wfile)
static_responder = StaticResponder(request, response, "static")
if static_responder.file:
response.set_status(response.HTTP_OK)
static_responder.prepare_response()
else:
response.add_header("Content-Type", "text/html")
response.add_header("Connection", "close")
response.set_body('<h1>Hello, world!</h1>')
response.send()
class ThreadedTCPServe(ThreadingMixIn, TCPServer):
pass
HOST, PORT = "127.0.0.1", 8000
TCPServer.allow_reuse_address = True
with TCPServer((HOST, PORT), HelloTCPServer) as s:
s.serve_forever()
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