Skip to content

Commit d8f5116

Browse files
committed
Merge branch 'main' of https://github.com/Jones-peter/jsweb
2 parents 59a0bf0 + bfb149d commit d8f5116

File tree

1 file changed

+20
-12
lines changed

1 file changed

+20
-12
lines changed

jsweb/app.py

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import asyncio
44
from .routing import Router, NotFound, MethodNotAllowed
55
from .request import Request
6-
from .response import Response, HTMLResponse, configure_template_env
6+
from .response import Response, HTMLResponse, configure_template_env, JSONResponse
77
from .auth import init_auth, get_current_user
88
from .middleware import StaticFilesMiddleware, DBSessionMiddleware, CSRFMiddleware
99
from .blueprints import Blueprint
@@ -79,9 +79,23 @@ def decorator(func):
7979

8080
async def _asgi_app_handler(self, scope, receive, send):
8181
req = scope['jsweb.request']
82+
8283
try:
8384
handler, params = self.router.resolve(req.path, req.method)
84-
85+
except NotFound as e:
86+
response = JSONResponse({"error": str(e)}, status_code=404)
87+
await response(scope, receive, send)
88+
return
89+
except MethodNotAllowed as e:
90+
response = JSONResponse({"error": str(e)}, status_code=405)
91+
await response(scope, receive, send)
92+
return
93+
except Exception as e:
94+
response = JSONResponse({"error": "Internal Server Error"}, status_code=500)
95+
await response(scope, receive, send)
96+
return
97+
98+
if handler:
8599
# Support both sync and async handlers
86100
if asyncio.iscoroutinefunction(handler):
87101
response = await handler(req, **params)
@@ -94,17 +108,11 @@ async def _asgi_app_handler(self, scope, receive, send):
94108
if not isinstance(response, Response):
95109
raise TypeError(f"View function did not return a Response object (got {type(response).__name__})")
96110

97-
except NotFound:
98-
response = HTMLResponse("<h1>404 Not Found</h1>", status_code=404)
99-
except MethodNotAllowed:
100-
response = HTMLResponse("<h1>405 Method Not Allowed</h1>", status_code=405)
101-
except Exception as e:
102-
response = HTMLResponse(f"<h1>500 Internal Server Error</h1><p>{e}</p>", status_code=500)
111+
if hasattr(req, 'new_csrf_token_generated') and req.new_csrf_token_generated:
112+
response.set_cookie("csrf_token", req.csrf_token, httponly=False, samesite='Lax')
103113

104-
if hasattr(req, 'new_csrf_token_generated') and req.new_csrf_token_generated:
105-
response.set_cookie("csrf_token", req.csrf_token, httponly=False, samesite='Lax')
106-
107-
await response(scope, receive, send)
114+
await response(scope, receive, send)
115+
return
108116

109117

110118
async def __call__(self, scope, receive, send):

0 commit comments

Comments
 (0)