routly 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- routly-0.1.0/PKG-INFO +100 -0
- routly-0.1.0/README.md +85 -0
- routly-0.1.0/pyproject.toml +32 -0
- routly-0.1.0/routly/__init__.py +5 -0
- routly-0.1.0/routly/conf/__init__.py +3 -0
- routly-0.1.0/routly/conf/settings.py +49 -0
- routly-0.1.0/routly/core/__init__.py +3 -0
- routly-0.1.0/routly/core/app.py +86 -0
- routly-0.1.0/routly/exceptions/__init__.py +24 -0
- routly-0.1.0/routly/exceptions/exceptions.py +86 -0
- routly-0.1.0/routly/exceptions/handler.py +80 -0
- routly-0.1.0/routly/exceptions/templates/debug.html +250 -0
- routly-0.1.0/routly/http/__init__.py +4 -0
- routly-0.1.0/routly/http/request.py +13 -0
- routly-0.1.0/routly/http/response.py +58 -0
- routly-0.1.0/routly/middleware/__init__.py +19 -0
- routly-0.1.0/routly/middleware/base.py +14 -0
- routly-0.1.0/routly/middleware/cors.py +98 -0
- routly-0.1.0/routly/middleware/csrf.py +99 -0
- routly-0.1.0/routly/middleware/gzip.py +47 -0
- routly-0.1.0/routly/middleware/manager.py +48 -0
- routly-0.1.0/routly/middleware/security.py +94 -0
- routly-0.1.0/routly/middleware/session.py +100 -0
- routly-0.1.0/routly/middleware/timing.py +21 -0
- routly-0.1.0/routly/routing/__init__.py +4 -0
- routly-0.1.0/routly/routing/route.py +26 -0
- routly-0.1.0/routly/routing/router.py +75 -0
- routly-0.1.0/routly/templating/__init__.py +3 -0
- routly-0.1.0/routly/templating/engine.py +34 -0
- routly-0.1.0/routly/templating/helpers.py +38 -0
- routly-0.1.0/routly.egg-info/PKG-INFO +100 -0
- routly-0.1.0/routly.egg-info/SOURCES.txt +45 -0
- routly-0.1.0/routly.egg-info/dependency_links.txt +1 -0
- routly-0.1.0/routly.egg-info/requires.txt +8 -0
- routly-0.1.0/routly.egg-info/top_level.txt +1 -0
- routly-0.1.0/setup.cfg +4 -0
- routly-0.1.0/tests/test_app.py +166 -0
- routly-0.1.0/tests/test_cors.py +126 -0
- routly-0.1.0/tests/test_csrf.py +143 -0
- routly-0.1.0/tests/test_gzip_middleware.py +62 -0
- routly-0.1.0/tests/test_http.py +62 -0
- routly-0.1.0/tests/test_middleware.py +109 -0
- routly-0.1.0/tests/test_routing.py +79 -0
- routly-0.1.0/tests/test_security_middleware.py +105 -0
- routly-0.1.0/tests/test_session_middleware.py +98 -0
- routly-0.1.0/tests/test_templating.py +68 -0
- routly-0.1.0/tests/test_timing_middleware.py +23 -0
routly-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: routly
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A lightweight, modern Python microframework for Web & REST APIs
|
|
5
|
+
Author: Abdulbosit Alijonov
|
|
6
|
+
Requires-Python: >=3.10
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
Requires-Dist: WebOb>=1.8.0
|
|
9
|
+
Requires-Dist: parse>=1.20.0
|
|
10
|
+
Requires-Dist: jinja2>=3.1.0
|
|
11
|
+
Requires-Dist: whitenoise>=6.0.0
|
|
12
|
+
Provides-Extra: dev
|
|
13
|
+
Requires-Dist: pytest>=8.0.0; extra == "dev"
|
|
14
|
+
Requires-Dist: gunicorn>=21.0.0; extra == "dev"
|
|
15
|
+
|
|
16
|
+
# Routly
|
|
17
|
+
|
|
18
|
+
A lightweight, modern Python microframework for **Web & REST APIs**.
|
|
19
|
+
|
|
20
|
+
Built from scratch with zero bloat, native WSGI compliance, and a developer-first design.
|
|
21
|
+
|
|
22
|
+
---
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
|
|
26
|
+
- **Fast & Expressive Routing:** Dynamic path matching with typed parameter extraction (`/users/{id}`).
|
|
27
|
+
- **First-Class REST API:** Automatic `dict` and `list` serialization to `application/json`, plus `(data, status_code)` return tuples.
|
|
28
|
+
- **Full REST Verbs:** Clean method decorators (`@app.get`, `@app.post`, `@app.put`, `@app.patch`, `@app.delete`).
|
|
29
|
+
- **Batteries-Included Middleware Pipeline:**
|
|
30
|
+
- `CsrfMiddleware` (Double-submit cookie pattern)
|
|
31
|
+
- `CorsMiddleware` (Preflight OPTIONS, customizable origins, methods, and credentials)
|
|
32
|
+
- `SecurityMiddleware` (`ALLOWED_HOSTS`, clickjacking, XSS, and MIME-sniffing protection)
|
|
33
|
+
- `SessionMiddleware` (Tamper-proof HMAC-SHA256 signed cookies)
|
|
34
|
+
- `GZipMiddleware` (Automatic response body compression)
|
|
35
|
+
- `ProcessTimeMiddleware` (Request execution timing in `X-Process-Time`)
|
|
36
|
+
- **HTTP Exception Hierarchy:** Django-inspired exceptions (`BadRequest`, `Unauthorized`, `Forbidden`, `NotFound`, `MethodNotAllowed`, `InternalServerError`, `abort(code, message)`).
|
|
37
|
+
- **Dark-Mode Debugger:** Tailwind CSS powered interactive traceback screen with request headers, client details, and traceback clipboard copy.
|
|
38
|
+
- **Content Negotiation:** Automatic JSON error responses for API consumers, interactive debugger for browser requests.
|
|
39
|
+
- **Jinja2 Templating:** Template inheritance with built-in `{{ static('...') }}` and `{{ csrf_input() }}` helpers.
|
|
40
|
+
- **Production Static Assets:** Native static file delivery powered by WhiteNoise.
|
|
41
|
+
- **Modular Settings:** Django-style configuration discovery via `ROUTLY_SETTINGS_MODULE` or `settings.py`.
|
|
42
|
+
- **100% WSGI Compliant:** Works seamlessly with Gunicorn, uWSGI, and any standard WSGI server.
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install -e .
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Quickstart
|
|
55
|
+
|
|
56
|
+
Create `app.py`:
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from routly import RoutlyApp
|
|
60
|
+
|
|
61
|
+
app = RoutlyApp()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@app.get("/")
|
|
65
|
+
def home(request):
|
|
66
|
+
return app.template("index.html")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@app.get("/api/users/{id}")
|
|
70
|
+
def get_user(request, id):
|
|
71
|
+
return {"id": id, "name": "Abdulbosit", "active": True}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@app.post("/api/users")
|
|
75
|
+
def create_user(request):
|
|
76
|
+
return {"status": "created", "user": request.json}, 201
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Run with Gunicorn:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
gunicorn -b 127.0.0.1:8000 app:app
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
---
|
|
86
|
+
|
|
87
|
+
## Testing
|
|
88
|
+
|
|
89
|
+
Run the test suite with pytest:
|
|
90
|
+
|
|
91
|
+
```bash
|
|
92
|
+
pytest tests/
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## License
|
|
98
|
+
|
|
99
|
+
Author: **Abdulbosit Alijonov**
|
|
100
|
+
Open-source under the MIT License.
|
routly-0.1.0/README.md
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# Routly
|
|
2
|
+
|
|
3
|
+
A lightweight, modern Python microframework for **Web & REST APIs**.
|
|
4
|
+
|
|
5
|
+
Built from scratch with zero bloat, native WSGI compliance, and a developer-first design.
|
|
6
|
+
|
|
7
|
+
---
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- **Fast & Expressive Routing:** Dynamic path matching with typed parameter extraction (`/users/{id}`).
|
|
12
|
+
- **First-Class REST API:** Automatic `dict` and `list` serialization to `application/json`, plus `(data, status_code)` return tuples.
|
|
13
|
+
- **Full REST Verbs:** Clean method decorators (`@app.get`, `@app.post`, `@app.put`, `@app.patch`, `@app.delete`).
|
|
14
|
+
- **Batteries-Included Middleware Pipeline:**
|
|
15
|
+
- `CsrfMiddleware` (Double-submit cookie pattern)
|
|
16
|
+
- `CorsMiddleware` (Preflight OPTIONS, customizable origins, methods, and credentials)
|
|
17
|
+
- `SecurityMiddleware` (`ALLOWED_HOSTS`, clickjacking, XSS, and MIME-sniffing protection)
|
|
18
|
+
- `SessionMiddleware` (Tamper-proof HMAC-SHA256 signed cookies)
|
|
19
|
+
- `GZipMiddleware` (Automatic response body compression)
|
|
20
|
+
- `ProcessTimeMiddleware` (Request execution timing in `X-Process-Time`)
|
|
21
|
+
- **HTTP Exception Hierarchy:** Django-inspired exceptions (`BadRequest`, `Unauthorized`, `Forbidden`, `NotFound`, `MethodNotAllowed`, `InternalServerError`, `abort(code, message)`).
|
|
22
|
+
- **Dark-Mode Debugger:** Tailwind CSS powered interactive traceback screen with request headers, client details, and traceback clipboard copy.
|
|
23
|
+
- **Content Negotiation:** Automatic JSON error responses for API consumers, interactive debugger for browser requests.
|
|
24
|
+
- **Jinja2 Templating:** Template inheritance with built-in `{{ static('...') }}` and `{{ csrf_input() }}` helpers.
|
|
25
|
+
- **Production Static Assets:** Native static file delivery powered by WhiteNoise.
|
|
26
|
+
- **Modular Settings:** Django-style configuration discovery via `ROUTLY_SETTINGS_MODULE` or `settings.py`.
|
|
27
|
+
- **100% WSGI Compliant:** Works seamlessly with Gunicorn, uWSGI, and any standard WSGI server.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install -e .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
|
|
39
|
+
## Quickstart
|
|
40
|
+
|
|
41
|
+
Create `app.py`:
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from routly import RoutlyApp
|
|
45
|
+
|
|
46
|
+
app = RoutlyApp()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@app.get("/")
|
|
50
|
+
def home(request):
|
|
51
|
+
return app.template("index.html")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@app.get("/api/users/{id}")
|
|
55
|
+
def get_user(request, id):
|
|
56
|
+
return {"id": id, "name": "Abdulbosit", "active": True}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@app.post("/api/users")
|
|
60
|
+
def create_user(request):
|
|
61
|
+
return {"status": "created", "user": request.json}, 201
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Run with Gunicorn:
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
gunicorn -b 127.0.0.1:8000 app:app
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
---
|
|
71
|
+
|
|
72
|
+
## Testing
|
|
73
|
+
|
|
74
|
+
Run the test suite with pytest:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
pytest tests/
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
---
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
Author: **Abdulbosit Alijonov**
|
|
85
|
+
Open-source under the MIT License.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "routly"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A lightweight, modern Python microframework for Web & REST APIs"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
authors = [
|
|
12
|
+
{ name = "Abdulbosit Alijonov" }
|
|
13
|
+
]
|
|
14
|
+
dependencies = [
|
|
15
|
+
"WebOb>=1.8.0",
|
|
16
|
+
"parse>=1.20.0",
|
|
17
|
+
"jinja2>=3.1.0",
|
|
18
|
+
"whitenoise>=6.0.0"
|
|
19
|
+
]
|
|
20
|
+
|
|
21
|
+
[project.optional-dependencies]
|
|
22
|
+
dev = [
|
|
23
|
+
"pytest>=8.0.0",
|
|
24
|
+
"gunicorn>=21.0.0"
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools.packages.find]
|
|
28
|
+
where = ["."]
|
|
29
|
+
include = ["routly*"]
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.package-data]
|
|
32
|
+
"*" = ["*.html"]
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import importlib
|
|
2
|
+
import os
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Any, List, Optional, Union
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Settings:
|
|
8
|
+
"""Manages application-wide configuration settings with environment-based module discovery."""
|
|
9
|
+
|
|
10
|
+
def __init__(self) -> None:
|
|
11
|
+
"""Initializes default settings and loads user-defined overrides."""
|
|
12
|
+
self.DEBUG: bool = True
|
|
13
|
+
self.SECRET_KEY: str = "routly-secret-key-default"
|
|
14
|
+
self.TEMPLATES: List[dict[str, Any]] = []
|
|
15
|
+
self.MIDDLEWARE: List[str] = []
|
|
16
|
+
self.ALLOWED_HOSTS: List[str] = ["*"]
|
|
17
|
+
self.STATIC_URL: str = "/static/"
|
|
18
|
+
self.STATIC_ROOT: Optional[Union[str, Path]] = None
|
|
19
|
+
|
|
20
|
+
self.SESSION_COOKIE_NAME: str = "session"
|
|
21
|
+
self.SESSION_COOKIE_MAX_AGE: int = 1209600
|
|
22
|
+
self.SESSION_COOKIE_PATH: str = "/"
|
|
23
|
+
self.SESSION_COOKIE_HTTPONLY: bool = True
|
|
24
|
+
self.SESSION_COOKIE_SAMESITE: str = "Lax"
|
|
25
|
+
self.SESSION_COOKIE_SECURE: bool = False
|
|
26
|
+
|
|
27
|
+
self.CSRF_COOKIE_NAME: str = "csrftoken"
|
|
28
|
+
self.CSRF_COOKIE_PATH: str = "/"
|
|
29
|
+
self.CSRF_COOKIE_HTTPONLY: bool = False
|
|
30
|
+
self.CSRF_COOKIE_SAMESITE: str = "Lax"
|
|
31
|
+
self.CSRF_COOKIE_SECURE: bool = False
|
|
32
|
+
|
|
33
|
+
self._setup()
|
|
34
|
+
|
|
35
|
+
def _setup(self) -> None:
|
|
36
|
+
"""Discovers and imports the user settings module specified by ROUTLY_SETTINGS_MODULE."""
|
|
37
|
+
settings_module: str = os.environ.get("ROUTLY_SETTINGS_MODULE", "settings")
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
user_settings = importlib.import_module(settings_module)
|
|
41
|
+
|
|
42
|
+
for key in dir(user_settings):
|
|
43
|
+
if key.isupper():
|
|
44
|
+
setattr(self, key, getattr(user_settings, key))
|
|
45
|
+
except ImportError:
|
|
46
|
+
pass
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
settings: Settings = Settings()
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from typing import Any, Callable, Dict, Iterable, Optional, Type, Union
|
|
2
|
+
from whitenoise import WhiteNoise
|
|
3
|
+
|
|
4
|
+
from routly.conf import settings
|
|
5
|
+
from routly.exceptions import (
|
|
6
|
+
HttpException,
|
|
7
|
+
InternalServerError,
|
|
8
|
+
MethodNotAllowed,
|
|
9
|
+
NotFound,
|
|
10
|
+
render_exception,
|
|
11
|
+
)
|
|
12
|
+
from routly.http import Request, Response, build_response, current_request
|
|
13
|
+
from routly.middleware import BaseMiddleware, MiddlewareManager
|
|
14
|
+
from routly.routing import Router
|
|
15
|
+
from routly.templating import TemplateEngine
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RoutlyApp(Router):
|
|
19
|
+
"""Central WSGI application class for Routly microframework."""
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
"""Initializes the template engine, middleware pipeline, and WhiteNoise static serving."""
|
|
23
|
+
super().__init__()
|
|
24
|
+
self.templates: TemplateEngine = TemplateEngine()
|
|
25
|
+
self.middleware: MiddlewareManager = MiddlewareManager()
|
|
26
|
+
self.wsgi_app: Callable[..., Iterable[bytes]] = self._dispatch
|
|
27
|
+
|
|
28
|
+
static_root = getattr(settings, "STATIC_ROOT", None)
|
|
29
|
+
if static_root:
|
|
30
|
+
self.wsgi_app = WhiteNoise(
|
|
31
|
+
self.wsgi_app,
|
|
32
|
+
root=str(static_root),
|
|
33
|
+
prefix=getattr(settings, "STATIC_URL", "/static/"),
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def __call__(
|
|
37
|
+
self, environ: Dict[str, Any], start_response: Callable[..., Any]
|
|
38
|
+
) -> Iterable[bytes]:
|
|
39
|
+
"""WSGI interface entry point, delegating to the wrapped WSGI pipeline."""
|
|
40
|
+
return self.wsgi_app(environ, start_response)
|
|
41
|
+
|
|
42
|
+
def _dispatch(
|
|
43
|
+
self, environ: Dict[str, Any], start_response: Callable[..., Any]
|
|
44
|
+
) -> Iterable[bytes]:
|
|
45
|
+
"""Dispatches an incoming WSGI request, executes handle_request, and starts response."""
|
|
46
|
+
request = Request(environ)
|
|
47
|
+
response = self.handle_request(request)
|
|
48
|
+
return response(environ, start_response)
|
|
49
|
+
|
|
50
|
+
def handle_request(self, request: Request) -> Response:
|
|
51
|
+
"""Processes an incoming HTTP request through middleware, route resolution, and handlers."""
|
|
52
|
+
current_request.set(request)
|
|
53
|
+
|
|
54
|
+
try:
|
|
55
|
+
response = self.middleware.process_request(request)
|
|
56
|
+
if response is not None:
|
|
57
|
+
return self.middleware.process_response(request, build_response(response))
|
|
58
|
+
|
|
59
|
+
handler, kwargs, error = self.resolve(request.path, request.method)
|
|
60
|
+
|
|
61
|
+
if error == 405:
|
|
62
|
+
raise MethodNotAllowed()
|
|
63
|
+
|
|
64
|
+
if error == 404 or handler is None:
|
|
65
|
+
raise NotFound()
|
|
66
|
+
|
|
67
|
+
response = build_response(handler(request, **kwargs))
|
|
68
|
+
except HttpException as exc:
|
|
69
|
+
response = render_exception(request, exc)
|
|
70
|
+
|
|
71
|
+
except Exception as exc:
|
|
72
|
+
response = render_exception(request, InternalServerError(exc=exc))
|
|
73
|
+
|
|
74
|
+
return self.middleware.process_response(request, response)
|
|
75
|
+
|
|
76
|
+
def template(
|
|
77
|
+
self, template_name: str, context: Optional[Dict[str, Any]] = None
|
|
78
|
+
) -> str:
|
|
79
|
+
"""Renders a Jinja2 template with context data."""
|
|
80
|
+
return self.templates.render(template_name, context)
|
|
81
|
+
|
|
82
|
+
def add_middleware(
|
|
83
|
+
self, middleware: Union[Type[BaseMiddleware], BaseMiddleware, str]
|
|
84
|
+
) -> None:
|
|
85
|
+
"""Registers a middleware class, instance, or dotted import string."""
|
|
86
|
+
self.middleware.add(middleware)
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from routly.exceptions.exceptions import (
|
|
2
|
+
HttpException,
|
|
3
|
+
BadRequest,
|
|
4
|
+
Unauthorized,
|
|
5
|
+
Forbidden,
|
|
6
|
+
NotFound,
|
|
7
|
+
MethodNotAllowed,
|
|
8
|
+
InternalServerError,
|
|
9
|
+
abort,
|
|
10
|
+
)
|
|
11
|
+
from routly.exceptions.handler import render_exception, render_debug_page
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"HttpException",
|
|
15
|
+
"BadRequest",
|
|
16
|
+
"Unauthorized",
|
|
17
|
+
"Forbidden",
|
|
18
|
+
"NotFound",
|
|
19
|
+
"MethodNotAllowed",
|
|
20
|
+
"InternalServerError",
|
|
21
|
+
"abort",
|
|
22
|
+
"render_exception",
|
|
23
|
+
"render_debug_page",
|
|
24
|
+
]
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
from typing import Dict, NoReturn, Optional, Type
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class HttpException(Exception):
|
|
5
|
+
"""Base class for all Routly HTTP exceptions."""
|
|
6
|
+
|
|
7
|
+
status_code: int = 500
|
|
8
|
+
default_message: str = "Internal Server Error"
|
|
9
|
+
default_title: str = "Server Error"
|
|
10
|
+
|
|
11
|
+
def __init__(
|
|
12
|
+
self,
|
|
13
|
+
message: Optional[str] = None,
|
|
14
|
+
title: Optional[str] = None,
|
|
15
|
+
exc: Optional[Exception] = None,
|
|
16
|
+
) -> None:
|
|
17
|
+
"""Initializes the HTTP exception with optional custom message, title, and underlying cause."""
|
|
18
|
+
self.message: str = message or self.default_message
|
|
19
|
+
self.title: str = title or self.default_title
|
|
20
|
+
self.exc: Optional[Exception] = exc
|
|
21
|
+
|
|
22
|
+
super().__init__(self.message)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class BadRequest(HttpException):
|
|
26
|
+
"""400 Bad Request exception."""
|
|
27
|
+
|
|
28
|
+
status_code: int = 400
|
|
29
|
+
default_message: str = "Bad Request"
|
|
30
|
+
default_title: str = "Bad Request"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class Unauthorized(HttpException):
|
|
34
|
+
"""401 Unauthorized exception."""
|
|
35
|
+
|
|
36
|
+
status_code: int = 401
|
|
37
|
+
default_message: str = "Unauthorized"
|
|
38
|
+
default_title: str = "Authentication Required"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Forbidden(HttpException):
|
|
42
|
+
"""403 Forbidden exception."""
|
|
43
|
+
|
|
44
|
+
status_code: int = 403
|
|
45
|
+
default_message: str = "Forbidden"
|
|
46
|
+
default_title: str = "Access Forbidden"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class NotFound(HttpException):
|
|
50
|
+
"""404 Not Found exception."""
|
|
51
|
+
|
|
52
|
+
status_code: int = 404
|
|
53
|
+
default_message: str = "Not Found"
|
|
54
|
+
default_title: str = "Page Not Found"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class MethodNotAllowed(HttpException):
|
|
58
|
+
"""405 Method Not Allowed exception."""
|
|
59
|
+
|
|
60
|
+
status_code: int = 405
|
|
61
|
+
default_message: str = "Method Not Allowed"
|
|
62
|
+
default_title: str = "HTTP Method Not Allowed"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class InternalServerError(HttpException):
|
|
66
|
+
"""500 Internal Server Error exception."""
|
|
67
|
+
|
|
68
|
+
status_code: int = 500
|
|
69
|
+
default_message: str = "Internal Server Error"
|
|
70
|
+
default_title: str = "Internal Server Error"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
STATUS_MAP: Dict[int, Type[HttpException]] = {
|
|
74
|
+
400: BadRequest,
|
|
75
|
+
401: Unauthorized,
|
|
76
|
+
403: Forbidden,
|
|
77
|
+
404: NotFound,
|
|
78
|
+
405: MethodNotAllowed,
|
|
79
|
+
500: InternalServerError,
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def abort(code: int, message: Optional[str] = None) -> NoReturn:
|
|
84
|
+
"""Raises an appropriate HttpException corresponding to the given HTTP status code."""
|
|
85
|
+
exc_class = STATUS_MAP.get(code, HttpException)
|
|
86
|
+
raise exc_class(message)
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import traceback
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import Any, Optional
|
|
4
|
+
from jinja2 import Template
|
|
5
|
+
|
|
6
|
+
from routly.conf import settings
|
|
7
|
+
from routly.exceptions.exceptions import HttpException, InternalServerError
|
|
8
|
+
from routly.http import Response
|
|
9
|
+
|
|
10
|
+
TEMPLATE_FILE: Path = Path(__file__).resolve().parent / "templates" / "debug.html"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def render_debug_page(
|
|
14
|
+
request: Any,
|
|
15
|
+
exc: Optional[Exception] = None,
|
|
16
|
+
status_code: int = 500,
|
|
17
|
+
status_text: str = "Server Error",
|
|
18
|
+
error_title: str = "Unhandled Exception",
|
|
19
|
+
) -> Response:
|
|
20
|
+
"""Renders the Tailwind CSS dark-mode interactive debugger page with traceback details."""
|
|
21
|
+
template_content = TEMPLATE_FILE.read_text(encoding="utf-8")
|
|
22
|
+
template = Template(template_content)
|
|
23
|
+
|
|
24
|
+
if exc is not None:
|
|
25
|
+
exc_type = type(exc).__name__
|
|
26
|
+
exc_value = str(exc)
|
|
27
|
+
tb_text = traceback.format_exc()
|
|
28
|
+
else:
|
|
29
|
+
exc_type = f"HTTP {status_code}"
|
|
30
|
+
exc_value = status_text
|
|
31
|
+
tb_text = None
|
|
32
|
+
|
|
33
|
+
html = template.render(
|
|
34
|
+
exc_type=exc_type,
|
|
35
|
+
exc_value=exc_value,
|
|
36
|
+
tb_text=tb_text,
|
|
37
|
+
request=request,
|
|
38
|
+
status_code=status_code,
|
|
39
|
+
status_text=status_text,
|
|
40
|
+
error_title=error_title,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
response = Response()
|
|
44
|
+
response.status_code = status_code
|
|
45
|
+
response.content_type = "text/html"
|
|
46
|
+
response.text = html
|
|
47
|
+
return response
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def render_exception(request: Any, exc: Exception) -> Response:
|
|
51
|
+
"""Renders an HTTP response for an exception, handling content negotiation and debug mode."""
|
|
52
|
+
if not isinstance(exc, HttpException):
|
|
53
|
+
http_exc = InternalServerError(message=str(exc), exc=exc)
|
|
54
|
+
else:
|
|
55
|
+
http_exc = exc
|
|
56
|
+
|
|
57
|
+
code: int = http_exc.status_code
|
|
58
|
+
message: str = http_exc.message
|
|
59
|
+
title: str = http_exc.title
|
|
60
|
+
underlying_exc: Exception = http_exc.exc or http_exc
|
|
61
|
+
|
|
62
|
+
is_json = "application/json" in request.headers.get(
|
|
63
|
+
"Accept", ""
|
|
64
|
+
) or "application/json" in (request.content_type or "")
|
|
65
|
+
if is_json:
|
|
66
|
+
res = Response(status_code=code)
|
|
67
|
+
res.json = {"error": title, "message": message, "status_code": code}
|
|
68
|
+
res.content_type = "application/json"
|
|
69
|
+
return res
|
|
70
|
+
|
|
71
|
+
if getattr(settings, "DEBUG", False):
|
|
72
|
+
return render_debug_page(
|
|
73
|
+
request,
|
|
74
|
+
exc=underlying_exc,
|
|
75
|
+
status_code=code,
|
|
76
|
+
status_text=message,
|
|
77
|
+
error_title=title,
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
return Response(message, status_code=code)
|