A Unix-style Python web framework: filesystem routing, flat files, messages and cron, with CGI's simplicity at modern speed.

0 downloads

Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Dan Quellhorst Replace multipart parser with stdlib-only implementation eb957a2 9 months, 2 weeks ago History
user.py · 2.2 KB · 81 lines
1"""User API - demonstrates hierarchical routing
2
3This file handles:
4- /user → list all users
5- /user/123 → get user 123
6- /user/123/posts → get posts for user 123
7"""
8import json
9from dbbasic_web.responses import json as json_response, text
10
11
12def handle(request):
13 """Route based on path_parts"""
14 path_parts = request["path_parts"]
15 method = request["method"]
16
17 # /user
18 if len(path_parts) == 1:
19 if method == "GET":
20 return list_users(request)
21 elif method == "POST":
22 return create_user(request)
23
24 # /user/{id}
25 elif len(path_parts) == 2:
26 user_id = path_parts[1]
27 if method == "GET":
28 return get_user(user_id)
29 elif method == "PUT":
30 return update_user(user_id, request)
31 elif method == "DELETE":
32 return delete_user(user_id)
33
34 # /user/{id}/posts
35 elif len(path_parts) == 3 and path_parts[2] == "posts":
36 user_id = path_parts[1]
37 return get_user_posts(user_id)
38
39 return text("Not Found", 404)
40
41
42def list_users(request):
43 """List all users"""
44 users = [
45 {"id": 1, "name": "Alice"},
46 {"id": 2, "name": "Bob"},
47 {"id": 3, "name": "Charlie"},
48 ]
49 return json_response(json.dumps({"users": users}))
50
51
52def get_user(user_id: str):
53 """Get a single user"""
54 # In a real app, fetch from database
55 user = {"id": int(user_id), "name": f"User {user_id}", "email": f"user{user_id}@example.com"}
56 return json_response(json.dumps({"user": user}))
57
58
59def create_user(request):
60 """Create a new user"""
61 # In a real app, parse body and save to database
62 return json_response(json.dumps({"status": "created", "id": 999}), status=201)
63
64
65def update_user(user_id: str, request):
66 """Update a user"""
67 return json_response(json.dumps({"status": "updated", "id": int(user_id)}))
68
69
70def delete_user(user_id: str):
71 """Delete a user"""
72 return json_response(json.dumps({"status": "deleted", "id": int(user_id)}))
73
74
75def get_user_posts(user_id: str):
76 """Get posts for a user"""
77 posts = [
78 {"id": 1, "user_id": int(user_id), "title": "First post"},
79 {"id": 2, "user_id": int(user_id), "title": "Second post"},
80 ]
81 return json_response(json.dumps({"posts": posts}))