patx/micropie
added example to show manual request handling
Commit d8c7f87 · patx · 01/26/2025 at 9:24PM
Comments
No comments yet.
Diff
diff --git a/examples/requests/app.py b/examples/requests/app.py
new file mode 100644
index 0000000..e996a5a
--- /dev/null
+++ b/examples/requests/app.py
@@ -0,0 +1,68 @@
+from MicroPie import Server
+
+# Request handlers defined outside the class
+
+def get_handler():
+ return b"Hello, GET request received!" # Convert to bytes
+
+def post_handler():
+ return b"Hello, POST request received!" # Convert to bytes
+
+def put_handler():
+ return b"Hello, PUT request received!" # Convert to bytes
+
+def patch_handler():
+ return b"Hello, PATCH request received!" # Convert to bytes
+
+def delete_handler():
+ return b"Hello, DELETE request received!" # Convert to bytes
+
+def head_handler():
+ # Return status 200 with empty body and proper headers
+ return 200, b"", [("Content-Type", "text/html")]
+
+def options_handler():
+ # Return the allowed methods in the response header and message in bytes
+ return 200, b"Allowed methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD", [
+ ("Allow", "GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD")
+ ]
+
+# Define the custom server application
+class MyApp(Server):
+
+ # Handle root URL requests and delegate based on HTTP method
+ def index(self):
+ return self.handle_request()
+
+ def handle_request(self):
+ # Map request methods to their corresponding handler functions
+ method_map = {
+ "GET": get_handler,
+ "POST": post_handler,
+ "PUT": put_handler,
+ "PATCH": patch_handler,
+ "DELETE": delete_handler,
+ "HEAD": head_handler,
+ "OPTIONS": options_handler,
+ }
+
+ # Check if the request method is supported and call the handler
+ if self.request in method_map:
+ response = method_map[self.request]()
+
+ # Ensure response is formatted correctly for WSGI
+ if isinstance(response, tuple):
+ status_code, response_body, headers = response
+ else:
+ status_code, response_body, headers = 200, response, [("Content-Type", "text/html")]
+
+ return status_code, response_body, headers
+
+ # Return 405 if the request method is not supported
+ return 405, b"405 Method Not Allowed", [("Content-Type", "text/html")]
+
+# Run the web server
+if __name__ == '__main__':
+ app = MyApp()
+ app.run()
+