-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
202 lines (167 loc) · 6.65 KB
/
server.py
File metadata and controls
202 lines (167 loc) · 6.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
"""
Tiny demo server for the htmx + Arrow-JS example.
Why this exists:
- htmx works best by making real HTTP requests for HTML fragments.
- A tiny Python server gives us a realistic demo without needing ASP.NET Core,
Node, Vite or any build tooling.
What this server now does:
- Serves the page shell at both / and /index.html
- Serves local static files such as /app.js and /README.md
- Returns HTML fragments from /fragment/search, /fragment/results and /fragment/picker
Why this revision matters:
- The earlier version only served / for the main page.
- Browsing directly to /index.html returned 404, which made the demo feel broken.
- This version behaves much more like a normal dev server and is therefore
easier to understand and harder to trip over.
In a real Razor Pages app, the fragment routes would usually be handlers,
controller actions or endpoints returning partial HTML.
"""
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
from urllib.parse import urlparse, unquote
import json
import mimetypes
ROOT = Path(__file__).parent.resolve()
SEARCH_ITEMS = [
{"name": "Alice Brown", "role": "Developer", "location": "London"},
{"name": "Ben Smith", "role": "Tester", "location": "Birmingham"},
{"name": "Chloe Jones", "role": "Analyst", "location": "Bristol"},
{"name": "Daniel Reed", "role": "Developer", "location": "Manchester"},
{"name": "Ella Green", "role": "Product Owner", "location": "Leeds"},
]
RESULT_ROWS = [
{
"name": "Alice Brown",
"score": 97,
"notesShort": "Strong API and Azure background.",
"notesLong": "Strong API and Azure background. Good stakeholder communication and consistent delivery across integration-heavy projects."
},
{
"name": "Daniel Reed",
"score": 91,
"notesShort": "Strong front-end and UX skills.",
"notesLong": "Strong front-end and UX skills. Comfortable shaping browser-side behaviour without over-engineering the stack."
},
{
"name": "Chloe Jones",
"score": 88,
"notesShort": "Solid analysis and stakeholder work.",
"notesLong": "Solid analysis and stakeholder work. Strong at turning business process into clear implementation choices."
},
]
PICKER_PAYLOAD = {
"available": ["English", "Maths", "Science", "History", "Geography", "Computing"],
"selected": ["Art"]
}
NOTIFICATION_CATEGORIES = ["Info", "Warning", "Success", "Error"]
def read_file_bytes(path: Path) -> bytes:
return path.read_bytes()
def static_response(path: Path):
body = read_file_bytes(path)
content_type, _ = mimetypes.guess_type(str(path))
if not content_type:
content_type = "application/octet-stream"
if content_type.startswith("text/") or content_type in {
"application/javascript",
"application/json",
"image/svg+xml",
}:
content_type += "; charset=utf-8"
return 200, content_type, body
def fragment_search() -> bytes:
return f"""
<section class="stack">
<div class="flash success">
This fragment came from the Python server route <code>/fragment/search</code>.
</div>
<div data-arrow-search
data-server-count="{len(SEARCH_ITEMS)}"
data-initial-term=""
data-initial-role="all"
data-items='{json.dumps(SEARCH_ITEMS)}'></div>
</section>
""".encode("utf-8")
def fragment_results() -> bytes:
return f"""
<section class="stack">
<div class="flash success">
This fragment came from the Python server route <code>/fragment/results</code>.
</div>
<div data-arrow-results
data-minimum-score="0"
data-rows='{json.dumps(RESULT_ROWS)}'></div>
</section>
""".encode("utf-8")
def fragment_picker() -> bytes:
return f"""
<section class="stack">
<div class="flash success">
This fragment came from the Python server route <code>/fragment/picker</code>.
</div>
<div data-arrow-picker
data-payload='{json.dumps(PICKER_PAYLOAD)}'></div>
</section>
""".encode("utf-8")
def fragment_notifications() -> bytes:
return f"""
<section class="stack">
<div class="flash success">
This fragment came from the Python server route <code>/fragment/notifications</code>.
</div>
<div data-arrow-notifications
data-categories='{json.dumps(NOTIFICATION_CATEGORIES)}'></div>
</section>
""".encode("utf-8")
class DemoHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed = urlparse(self.path)
path = parsed.path
# Main page shell. Support both / and /index.html so the demo behaves
# like a typical development server.
if path in {"/", "/index.html"}:
status, content_type, body = static_response(ROOT / "index.html")
self.respond(status, content_type, body)
return
# Dynamic fragment endpoints used by htmx.
if path == "/fragment/search":
self.respond(200, "text/html; charset=utf-8", fragment_search())
return
if path == "/fragment/results":
self.respond(200, "text/html; charset=utf-8", fragment_results())
return
if path == "/fragment/picker":
self.respond(200, "text/html; charset=utf-8", fragment_picker())
return
if path == "/fragment/notifications":
self.respond(200, "text/html; charset=utf-8", fragment_notifications())
return
# Generic static-file serving for local assets in the demo folder.
# This means files such as /app.js will work without needing a new route.
# The path.resolve() check prevents escaping above the demo folder.
candidate = (ROOT / unquote(path.lstrip("/"))).resolve()
if candidate.is_file() and (candidate == ROOT or ROOT in candidate.parents):
status, content_type, body = static_response(candidate)
self.respond(status, content_type, body)
return
self.respond(404, "text/plain; charset=utf-8", b"Not found")
def log_message(self, format, *args):
# Keep console output tidy for a demo.
pass
def respond(self, status: int, content_type: str, body: bytes):
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
server = HTTPServer(("127.0.0.1", 8000), DemoHandler)
print("Demo server running at http://127.0.0.1:8000")
print("You can open either /")
print("or /index.html")
print("Press Ctrl+C to stop")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopping server...")
finally:
server.server_close()