/
syunya
/
HTTP-server
Обзор
Документация
Войти
/
syunya
/
HTTP-server
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
simple-http-server/server.py
118 строк
3 KB
syunya
create: README.md, update: routes.py, server.py, style.css, 404.html, index.html
22 май 2026, 20:53
Верифицирован
22 май 2026, 20:53
83ef0ce
Код
Авторство
О чём код?
import socket import threading import os import json from routes import routes HOST = "127.0.0.1" PORT = 8080 def load_file(filepath): with open(filepath, "r", encoding="utf-8") as file: return file.read() def create_response(status_code, content, content_type="text/html"): status_messages = { 200: "OK", 404: "Not Found", 500: "Internal Server Error" } response = f"HTTP/1.1 {status_code} {status_messages[status_code]}\r\n" response += f"Content-Type: {content_type}; charset=utf-8\r\n" response += "Connection: close\r\n\r\n" response += content return response.encode("utf-8") def handle_client(client_socket, client_address): print(f"[НОВОЕ ПОДКЛЮЧЕНИЕ] {client_address}") try: request = client_socket.recv(4096).decode("utf-8") if not request: client_socket.close() return first_line = request.split("\n")[0] method, path, _ = first_line.split() print(f"[ЗАПРОС] {method} {path}") # Главная страница if path == "/": content = load_file("templates/index.html") response = create_response(200, content) # CSS elif path == "/static/style.css": content = load_file("static/style.css") response = create_response(200, content, "text/css") # JSON API elif path == "/api/data": data = { "server": "Custom Python HTTP Server", "status": "running", "author": "Student Project" } response = create_response( 200, json.dumps(data, ensure_ascii=False, indent=4), "application/json" ) # Пользовательские маршруты elif path in routes: response = create_response(200, routes[path]) # 404 else: content = load_file("templates/404.html") response = create_response(404, content) client_socket.sendall(response) except Exception as e: print("[ОШИБКА]", e) response = create_response( 500, "<h1>500 Internal Server Error</h1>" ) client_socket.sendall(response) finally: client_socket.close() print(f"[ОТКЛЮЧЕНИЕ] {client_address}") def start_server(): server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind((HOST, PORT)) server.listen(5) print("=" * 50) print(f"Сервер запущен: http://{HOST}:{PORT}") print("=" * 50) while True: client_socket, client_address = server.accept() client_thread = threading.Thread( target=handle_client, args=(client_socket, client_address) ) client_thread.start() if __name__ == "__main__": start_server()