/
liquid-g
/
liquid-code
Обзор
Документация
Войти
/
liquid-g
/
liquid-code
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/liquidcode/middleware/static.py
68 строк
2 KB
User
ci: настроен Black и flake8 для автоматического форматирования кода
04 июл 2026, 08:14
04 июл 2026, 08:14
4778ed6
Код
Авторство
О чём код?
""" Middleware для раздачи статических файлов. """ import logging import mimetypes import os from typing import Callable from .base import Middleware from ..contracts import Request, Response from ..http import HttpResponse logger = logging.getLogger(__name__) class StaticFilesMiddleware(Middleware): """ Отдаёт статические файлы из указанной директории по заданному префиксу. Args: directory: Путь к папке со статикой (по умолчанию 'public'). prefix: URL-префикс (по умолчанию '/static'). """ def __init__(self, directory: str = "public", prefix: str = "/static"): self.directory = os.path.abspath(directory) self.prefix = prefix.rstrip("/") def __call__( self, request: Request, call_next: Callable[[Request], Response] ) -> Response: path = request.get_path() if not path.startswith(self.prefix): return call_next(request) # Убираем префикс relative_path = path[len(self.prefix) :].lstrip("/") if not relative_path: return call_next(request) # Строим абсолютный путь file_path = os.path.join(self.directory, relative_path) # Проверяем, что файл внутри директории if not os.path.abspath(file_path).startswith(self.directory): logger.warning( f"Попытка доступа к файлу вне статической директории: {file_path}" ) return call_next(request) if not os.path.isfile(file_path): return call_next(request) # Определяем MIME-тип mime_type, _ = mimetypes.guess_type(file_path) if mime_type is None: mime_type = "application/octet-stream" try: with open(file_path, "rb") as f: content = f.read() logger.info(f"Статика: {path} → {file_path} ({mime_type})") return HttpResponse( content, status=200, headers={"Content-Type": mime_type} ) except Exception as e: logger.error(f"Ошибка чтения статического файла {file_path}: {e}") return call_next(request)