π p4: scaffold demos differentiators β query_async, native_async, sse_native
swadhinbiswas committed 2 months ago
f05b19c
1 parent d663625
commit f05b19c
1 file changed
+32 -1
Showing 1 changed file+32-1
βΌcrates/justapi-cli/src/main.rs
+32-1
| @@ -906,7 +906,7 @@ def root(request): | ||
906 | 906 | |
907 | 907 | Database backend: {db_kind} (URL: {db_url}) |
908 | 908 | """ |
909 | -from justapi import JustAPIApp, Schema, HTTPException | |
909 | +from justapi import JustAPIApp, Schema, HTTPException, native_async | |
910 | 910 | from pydantic import Field |
911 | 911 | |
912 | 912 | app = JustAPIApp(title="{name}", version="0.1.0") |
| @@ -960,6 +960,37 @@ def create_item(request): | ||
960 | 960 | return {{"message": "Item created successfully", "name": name, "qty": qty}} |
961 | 961 | |
962 | 962 | |
963 | +@app.get("/items/{{item_id}}/async") | |
964 | +async def get_item_async(request, item_id: int): | |
965 | + """Async handler with a NATIVE async DB query (ADR-093). | |
966 | + | |
967 | + `query_async` runs the SQL on the DB's own tokio runtime with the GIL | |
968 | + released β the asyncio loop is never blocked, so slow queries (Postgres, | |
969 | + network DBs) do not serialize other requests. | |
970 | + """ | |
971 | + rows = await app.db.query_async("SELECT * FROM items WHERE id = ?", [item_id]) | |
972 | + if not rows: | |
973 | + raise HTTPException(status_code=404, detail=f"Item {{item_id}} not found") | |
974 | + return rows[0] | |
975 | + | |
976 | + | |
977 | +@app.post("/items/{{item_id}}/restock", body_schema=ItemCreate) | |
978 | +@native_async | |
979 | +async def restock(request, item_id: int): | |
980 | + """native_async handler: framework ops (DB) run in Rust (ADR-089).""" | |
981 | + data = request.json() | |
982 | + affected = await app.db.execute_async( | |
983 | + "UPDATE items SET qty = qty + ? WHERE id = ?", | |
984 | + [data.get("qty", 1), item_id], | |
985 | + ) | |
986 | + return {{"message": f"Item {{item_id}} restocked", "affected": affected}} | |
987 | + | |
988 | + | |
989 | +# Rust-native SSE stream: events generated entirely in Rust, no Python per | |
990 | +# event (ADR-088). `curl -N http://localhost:8080/events` streams 100 events. | |
991 | +app.sse_native("/events", count=100, interval_ms=50) | |
992 | + | |
993 | + | |
963 | 994 | @app.delete("/items/{{item_id}}") |
964 | 995 | def delete_item(request, item_id: int): |
965 | 996 | """Delete an item by ID.""" |
966 | 997 | |