Custom Request Handlers with BaseHTTPRequestHandler
Subclassing `http.server.BaseHTTPRequestHandler` lets you intercept requests. Define `do_GET()` and `do_POST()` methods, send response codes with `.send_response(200)`, and stream response bytes with `.wfile.write()` 📡.
from http.server import BaseHTTPRequestHandler
class CustomHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(b'{"status": "online"}')
print("CustomHandler intercepts HTTP requests directly at the socket level 📡")
# 37. Custom Request Handlers with BaseHTTPRequestHandler Subclassing `http.server.BaseHTTPRequestHandler` lets you intercept requests. Define `do_GET()` and `do_POST()` methods, send response codes with `.send_response(200)`, and stream response bytes with `.wfile.write()` 📡. ```python from http.server import BaseHTTPRequestHandler class CustomHandler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-Type", "application/json") self.end_headers() self.wfile.write(b'{"status": "online"}') print("CustomHandler intercepts HTTP requests directly at the socket level 📡") ``` Under the hood, `self.rfile` is the incoming request socket stream and `self.wfile` is the outgoing client response socket stream! 📡 --- ### Question Which method on `BaseHTTPRequestHandler` must be called to mark the completion of response headers before writing the response body? 🧠- [ ] a. `self.end_headers()` 📡 - [ ] b. `self.flush()` - [ ] c. `self.close_headers()` - [ ] d. `self.commit()` --- ### Challenge Create class `HealthHandler(BaseHTTPRequestHandler)` with method `format_json_response(data)`. It should return `json.dumps(data).encode("utf-8")`. Test with `{"ok": True}` and print decoded output. 🎯 <details> <summary>Solution</summary> ```python from http.server import BaseHTTPRequestHandler import json class HealthHandler(BaseHTTPRequestHandler): @staticmethod def format_json_response(data): return json.dumps(data).encode("utf-8") res = HealthHandler.format_json_response({"ok": True}) print(res.decode()) ``` </details>