This repository has been archived on 2026-11-17. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
pythonwebserver/requestHandler.py
2020-10-30 19:15:21 +01:00

37 lines
1.4 KiB
Python

from header import *
from os.path import isfile, isdir
from config import *
import traceback
def handleRequest(request_data, client_connection):
try:
path = request_data.split("\n")[0].replace("GET ", "").split(" HTTP/")[0]
if path == "/":
path = "/index.html"
if not isfile(baseFolder + path) and not isdir(baseFolder + path):
f = open(baseFolder + "/404.html", "rb")
data = f.read()
client_connection.sendall(
buildHeader(404, "html", len(data)) + data)
client_connection.close()
else:
if isdir(baseFolder + path):
if path[-1] == "/":
path = path + "index.html"
else:
client_connection.sendall((headers["301"] + "Location: " + path + "/\n\n").encode("utf-8"))
client_connection.close()
return
f = open(baseFolder + path, "rb")
data = f.read()
f.close()
client_connection.sendall(buildHeader(200, path.split(".")[-1], len(data)) + data)
client_connection.close()
except:
traceback.print_exc()
client_connection.sendall(
buildHeader(500, "plain", len("Internal Error".encode("utf-8"))) + "Internal Error".encode("utf-8"))
client_connection.close()