askrobots / dbbasic-web
Public
A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.
Dan Quellhorst
Replace multipart parser with stdlib-only implementation
eb957a2
9 months, 2 weeks ago
History
asgi.py · 3.2 KB · 108 lines
| 1 | """ASGI application - the heart of dbbasic-web""" |
| 2 | import json |
| 3 | from .router import route |
| 4 | from .sse import sse_counter |
| 5 | from .websocket import hub |
| 6 | |
| 7 | |
| 8 | async def app(scope, receive, send): |
| 9 | """Main ASGI application""" |
| 10 | |
| 11 | if scope["type"] == "http": |
| 12 | await http_handler(scope, receive, send) |
| 13 | elif scope["type"] == "websocket": |
| 14 | await websocket_handler(scope, receive, send) |
| 15 | elif scope["type"] == "lifespan": |
| 16 | await lifespan_handler(scope, receive, send) |
| 17 | |
| 18 | |
| 19 | async def http_handler(scope, receive, send): |
| 20 | """Handle HTTP requests""" |
| 21 | path = scope["path"] |
| 22 | |
| 23 | # Special routes for SSE |
| 24 | if path == "/sse/counter": |
| 25 | await sse_counter(scope, receive, send) |
| 26 | return |
| 27 | |
| 28 | # Read request body for POST/PUT requests |
| 29 | body = b"" |
| 30 | while True: |
| 31 | message = await receive() |
| 32 | if message["type"] == "http.request": |
| 33 | body += message.get("body", b"") |
| 34 | if not message.get("more_body", False): |
| 35 | break |
| 36 | elif message["type"] == "http.disconnect": |
| 37 | return |
| 38 | |
| 39 | # Normal routing through filesystem router |
| 40 | status, headers, body_parts = route(scope, body) |
| 41 | |
| 42 | # Convert to ASGI format |
| 43 | headers_asgi = [(k.encode() if isinstance(k, str) else k, |
| 44 | v.encode() if isinstance(v, str) else v) |
| 45 | for k, v in headers] |
| 46 | |
| 47 | await send({ |
| 48 | "type": "http.response.start", |
| 49 | "status": status, |
| 50 | "headers": headers_asgi, |
| 51 | }) |
| 52 | |
| 53 | for part in body_parts: |
| 54 | await send({ |
| 55 | "type": "http.response.body", |
| 56 | "body": part if isinstance(part, bytes) else part.encode(), |
| 57 | }) |
| 58 | |
| 59 | |
| 60 | async def websocket_handler(scope, receive, send): |
| 61 | """Handle WebSocket connections""" |
| 62 | await send({"type": "websocket.accept"}) |
| 63 | |
| 64 | # Extract room from path or query string |
| 65 | path = scope["path"] |
| 66 | room = path.split("/")[-1] if "/" in path else "default" |
| 67 | |
| 68 | # Create a simple wrapper for the WebSocket |
| 69 | class WSWrapper: |
| 70 | async def send_text(self, message): |
| 71 | await send({"type": "websocket.send", "text": message}) |
| 72 | |
| 73 | ws = WSWrapper() |
| 74 | await hub.join(room, ws) |
| 75 | |
| 76 | try: |
| 77 | while True: |
| 78 | message = await receive() |
| 79 | |
| 80 | if message["type"] == "websocket.disconnect": |
| 81 | break |
| 82 | |
| 83 | if message["type"] == "websocket.receive": |
| 84 | # Echo or broadcast received messages |
| 85 | if "text" in message: |
| 86 | try: |
| 87 | data = json.loads(message["text"]) |
| 88 | await hub.broadcast(room, data) |
| 89 | except json.JSONDecodeError: |
| 90 | await ws.send_text(json.dumps({"error": "Invalid JSON"})) |
| 91 | |
| 92 | finally: |
| 93 | await hub.leave(room, ws) |
| 94 | |
| 95 | |
| 96 | async def lifespan_handler(scope, receive, send): |
| 97 | """Handle application lifecycle events""" |
| 98 | while True: |
| 99 | message = await receive() |
| 100 | |
| 101 | if message["type"] == "lifespan.startup": |
| 102 | # Startup logic here (open database connections, etc.) |
| 103 | await send({"type": "lifespan.startup.complete"}) |
| 104 | |
| 105 | elif message["type"] == "lifespan.shutdown": |
| 106 | # Shutdown logic here (close connections, etc.) |
| 107 | await send({"type": "lifespan.shutdown.complete"}) |
| 108 | return |