forked from Shifty/pyserveX
fix: Update max-line-length in .flake8 and refactor routing and server code for improved readability and functionality
This commit is contained in:
parent
84cd1c974f
commit
6b157d7626
2
.flake8
2
.flake8
@ -1,4 +1,4 @@
|
||||
[flake8]
|
||||
max-line-length = 100
|
||||
max-line-length = 120
|
||||
exclude = __pycache__,.git,.venv,venv,build,dist
|
||||
ignore = E203,W503
|
||||
|
||||
@ -8,11 +8,13 @@ from .logging_utils import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class RouteMatch:
|
||||
def __init__(self, config: Dict[str, Any], params: Optional[Dict[str, str]] = None):
|
||||
self.config = config
|
||||
self.params = params or {}
|
||||
|
||||
|
||||
class Router:
|
||||
def __init__(self, static_dir: str = "./static"):
|
||||
self.static_dir = Path(static_dir)
|
||||
@ -82,7 +84,8 @@ class RequestHandler:
|
||||
|
||||
async def _process_route(self, request: Request, route_match: RouteMatch) -> Response:
|
||||
config = route_match.config
|
||||
path = request.url.path
|
||||
# HINT: Not using it right now
|
||||
# path = request.url.path
|
||||
|
||||
if "return" in config:
|
||||
status_text = config["return"]
|
||||
@ -95,7 +98,7 @@ class RequestHandler:
|
||||
|
||||
content_type = config.get("content_type", "text/plain")
|
||||
return PlainTextResponse(text, status_code=status_code,
|
||||
media_type=content_type)
|
||||
media_type=content_type)
|
||||
|
||||
if "proxy_pass" in config:
|
||||
return await self._handle_proxy(request, config, route_match.params)
|
||||
@ -162,7 +165,7 @@ class RequestHandler:
|
||||
return PlainTextResponse("404 Not Found", status_code=404)
|
||||
|
||||
async def _handle_proxy(self, request: Request, config: Dict[str, Any],
|
||||
params: Dict[str, str]) -> Response:
|
||||
params: Dict[str, str]) -> Response:
|
||||
# TODO: Реализовать полноценное проксирование
|
||||
proxy_url = config["proxy_pass"]
|
||||
|
||||
|
||||
@ -4,8 +4,8 @@ import time
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response, PlainTextResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.routing import Route
|
||||
from starlette.types import ASGIApp, Receive, Scope, Send
|
||||
from pathlib import Path
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
@ -17,22 +17,28 @@ from . import __version__
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class PyServeMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app, extension_manager: ExtensionManager):
|
||||
super().__init__(app)
|
||||
class PyServeMiddleware:
|
||||
def __init__(self, app: ASGIApp, extension_manager: ExtensionManager):
|
||||
self.app = app
|
||||
self.extension_manager = extension_manager
|
||||
self.access_logger = get_logger('pyserve.access')
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http":
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
start_time = time.time()
|
||||
request = Request(scope, receive)
|
||||
response = await self.extension_manager.process_request(request)
|
||||
|
||||
if response is None:
|
||||
response = await call_next(request)
|
||||
await self.app(scope, receive, send)
|
||||
return
|
||||
|
||||
response = await self.extension_manager.process_response(request, response)
|
||||
|
||||
response.headers["Server"] = f"pyserve/{__version__}"
|
||||
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
method = request.method
|
||||
path = str(request.url.path)
|
||||
@ -44,7 +50,7 @@ class PyServeMiddleware(BaseHTTPMiddleware):
|
||||
|
||||
self.access_logger.info(f"{client_ip} - {method} {path} - {status_code} - {process_time}ms")
|
||||
|
||||
return response
|
||||
await response(scope, receive, send)
|
||||
|
||||
|
||||
class PyServeServer:
|
||||
@ -58,7 +64,7 @@ class PyServeServer:
|
||||
|
||||
def _setup_logging(self) -> None:
|
||||
self.config.setup_logging()
|
||||
logger.info("PyServe сервер инициализирован")
|
||||
logger.info("PyServe server initialized")
|
||||
|
||||
def _load_extensions(self) -> None:
|
||||
for ext_config in self.config.extensions:
|
||||
@ -71,7 +77,18 @@ class PyServeServer:
|
||||
routes = [
|
||||
Route("/health", self._health_check, methods=["GET"]),
|
||||
Route("/metrics", self._metrics, methods=["GET"]),
|
||||
Route("/{path:path}", self._catch_all, methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]),
|
||||
Route(
|
||||
"/{path:path}",
|
||||
self._catch_all,
|
||||
methods=[
|
||||
"GET",
|
||||
"POST",
|
||||
"PUT",
|
||||
"DELETE",
|
||||
"PATCH",
|
||||
"OPTIONS"
|
||||
]
|
||||
),
|
||||
]
|
||||
|
||||
self.app = Starlette(routes=routes)
|
||||
@ -132,8 +149,7 @@ class PyServeServer:
|
||||
self._ensure_directories()
|
||||
ssl_context = self._create_ssl_context()
|
||||
|
||||
uvicorn_config = {
|
||||
"app": self.app,
|
||||
uvicorn_config: Dict[str, Any] = {
|
||||
"host": self.config.server.host,
|
||||
"port": self.config.server.port,
|
||||
"log_level": "critical",
|
||||
@ -154,7 +170,8 @@ class PyServeServer:
|
||||
logger.info(f"Starting PyServe server at {protocol}://{self.config.server.host}:{self.config.server.port}")
|
||||
|
||||
try:
|
||||
uvicorn.run(**uvicorn_config)
|
||||
assert self.app is not None, "App not initialized"
|
||||
uvicorn.run(self.app, **uvicorn_config)
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Received shutdown signal")
|
||||
except Exception as e:
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user