From 014cdd80e221918db3f2d25c66f9e75592f9074e Mon Sep 17 00:00:00 2001 From: 0880 <98263509+0880880@users.noreply.github.com> Date: Sat, 17 Jan 2026 18:14:20 +0330 Subject: [PATCH] Update HTTPResponse major changes --- slow/slow.py | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/slow/slow.py b/slow/slow.py index b164302..ed04159 100644 --- a/slow/slow.py +++ b/slow/slow.py @@ -259,33 +259,46 @@ class App: def HTTPResponse( - content: str, status=200, content_type="text/plain; charset=utf-8", headers=[] + request: Request, + content: str, + status=200, + content_type="text/plain; charset=utf-8", + headers=[], ) -> bytes: - global AccessControlAllowOrigin - head: str = f"HTTP/1.1 {status} {http.client.responses.get(status, 'Unkown Status Code')}\r\nContent-Type: {content_type}\r\n" - head += f"Access-Control-Allow-Origin: {AccessControlAllowOrigin}\r\n" # CORS - head += "Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS\r\n" # CORS + content_bytes = content.encode(encoding="utf-8") + head: str = f"HTTP/1.1 {status} {http.client.responses.get(status, 'Unkown Status Code')}\r\nContent-Type: {content_type}\r\nContent-Length: {len(content_bytes)}\r\n" + if ( + "origin" in request.headers + and not request.app.CORS.Disabled + and request.headers.get("origin") in request.app.CORS.Origins + ): + head += ( + f"Access-Control-Allow-Origin: {request.headers.get('origin')}\r\n" # CORS + ) + head += f"Access-Control-Allow-Methods: {','.join(request.app.CORS.Methods)}\r\n" # CORS + head += "Access-Control-Allow-Headers: Content-Type,Authorization\r\n" # CORS + head += "Vary: Origin\r\n" head += "\r\n".join(headers) + ("\r\n" if len(headers) > 0 else "") head += "\r\n" - return (head + content).encode(encoding="utf-8") + return head.encode(encoding="utf-8") + content_bytes _value_pattern = re.compile(r"\{\{\s*([a-zA-Z_][a-zA-Z_0-9]*)\s*\}\}") -def render(file: str | Path, variables: dict[str, Any] = {}) -> bytes: +def render(request: Request, file: str | Path, variables: dict[str, Any] = {}) -> bytes: if isinstance(file, str): file = Path(file) content: str = file.read_text(encoding="utf-8") for m in _value_pattern.findall(content): if m in variables: content = re.sub(r"\{\{\s*" + m + r"\s*\}\}", variables[m], content) - return HTTPResponse(content, content_type="text/html; charset=utf-8") + return HTTPResponse(request, content, content_type="text/html; charset=utf-8") -def JSONResponse(d: dict, status=200) -> bytes: +def JSONResponse(request: Request, d: dict, status=200) -> bytes: return HTTPResponse( - json.dumps(d), status=status, content_type="text/json; charset=utf-8" + request, json.dumps(d), status=status, content_type="text/json; charset=utf-8" ) @@ -301,6 +314,6 @@ def JSONAPI(func): ): return JSONResponse(result[1], result[0]) raise RuntimeError("Return value of JSONAPI route is not a dictionary") - return JSONResponse(result) + return JSONResponse(args[0], result) return wrapper