updated readme to include streaming example and info on websockets integration

Commit cbb0d5d · patx · 01/22/2025 at 7:38PM

Changeset
cbb0d5d7538283cb594e6d63a64c5e209e561eab
Parents
f70cf12a38a61314d35beb4f538ffa7def118bac

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/README.md b/README.md
index 97279da..38e460f 100644
--- a/README.md
+++ b/README.md
@@ -235,6 +235,48 @@ http://127.0.0.1:8080/static/style.css
 ```
 Note that this feature is only available for the default `run` method which uses `http.server` and does not currently work with the `wsgi_app` method. An easy work around is to use something like [GitHub Pages](https://pages.github.com/) to serve your static content and keep everything secure. You can also implement static files with other servers like gunicorn + nginx.
 
+### **8. Streaming Responses and WebSockets**
+
+#### **Streaming Response Support**
+MicroPie provides support for streaming responses, allowing you to send data to the client in chunks instead of all at once. This is particularly useful for scenarios where data is generated or processed over time, such as live feeds, large file downloads, or incremental data generation.
+
+#### How It Works
+Streaming is supported through the `wsgi_app` method, making it compatible with WSGI servers like **Gunicorn**. When a route handler returns a generator or an iterable (excluding strings), MicroPie automatically streams the response to the client. *Note, streaming is only supported via WSGI:* The built-in `run` method, which relies on Python's `http.server`, does not support streaming responses. Using the built-in server will result in the entire response being buffered before being sent to the client. *Session handling remains functional* when using streaming responses via WSGI, ensuring persistent state across streamed requests.
+
+With the following saved as `app.py`:
+```python
+import time
+from MicroPie import Server
+
+class Root(Server):
+
+    def index(self):
+        def generator():
+            for i in range(1, 6):
+                yield f"Chunk {i}\n"
+                time.sleep(1)  # Simulate slow processing or data generation
+        return generator()
+
+app = Root()
+wsgi_app = app.wsgi_app
+```
+Run your application with `gunicorn app:wsgi_app`. For best performance with streaming, consider tuning Gunicorn settings such as worker types (e.g., `--worker-class gevent`) to handle long-lived connections efficiently.
+
+#### **WebSockets Integration**
+MicroPie applications can seamlessly integrate **WebSockets** by running a separate WebSocket server using Python’s `websockets` library. This enables real-time, bidirectional communication between clients and the server, independent of the HTTP server being used. To get started with WebSockets in MicroPie, ensure you have the `websockets` package installed `pip install websockets`.
+
+#### How It Works
+
+- **The HTTP server (MicroPie)** handles regular web requests and serves the frontend.
+- **A separate WebSocket server** runs concurrently to handle real-time communication.
+- Clients connect to the WebSocket server via the frontend and exchange messages asynchronously.
+- Since the WebSocket server operates separately, it works regardless of whether the MicroPie HTTP server is running via the built-in `run` method (using `http.server`) or a production-grade WSGI server such as **Gunicorn**.
+- **Threading Considerations:** Since the WebSocket server runs in a separate thread, developers should handle shared resources carefully to avoid concurrency issues.
+- **Port Management:** The WebSocket server must run on a different port than the HTTP server to avoid conflicts.
+- **Client Compatibility:** Ensure that clients support WebSockets when implementing features relying on real-time communication.
+
+**For a full example showing `websockets` and MicroPie check out the [chatroom example](https://github.com/patx/micropie/tree/main/examples/chatroom).**
+
 ## **API Reference**
 
 ### Class: Server
@@ -261,15 +303,15 @@ Validates incoming requests for both GET and POST methods based on query and bod
 WSGI-compliant method for parsing requests and returning responses. Ideal for production deployment using WSGI servers.
 
 ## **Examples**
-Check out the [examples folder](https://github.com/patx/micropie/tree/main/examples) for more advanced usage, including template rendering, session usage, websockets and form handling.
+Check out the [examples folder](https://github.com/patx/micropie/tree/main/examples) for more advanced usage, including template rendering, session usage, websockets, streaming and form handling.
 
 ## **Feature Comparison: MicroPie, Flask, CherryPy, and Bottle**
 
 | Feature             | MicroPie  | Flask     | CherryPy  | Bottle     | Django     |
-|--------------------|-----------|-----------|-----------|------------|-------------|
-| **Ease of Use**     | Very Easy  | Easy      | Easy      | Easy       | Moderate  |
+|---------------------|-----------|-----------|-----------|------------|------------|
+| **Ease of Use**     | Very Easy | Easy      | Easy      | Easy       | Moderate   |
 | **Routing**         | Automatic | Manual    | Manual    | Manual     | Automatic  |
-| **Template Engine** | Jinja2     | Jinja2    | None      | SimpleTpl  | Django Templating |
+| **Template Engine** | Jinja2    | Jinja2    | None      | SimpleTpl  | Django Templating |
 | **Session Handling**| Built-in  | Extension | Built-in  | Plugin     | Built-in   |
 | **Request Handling**| Simple    | Flexible  | Advanced  | Simple     | Advanced   |
 | **Performance**     | High [^1] | High     | Moderate   | High       | Moderate   |
diff --git a/examples/chatroom/app.py b/examples/chatroom/app.py
new file mode 100644
index 0000000..c0303a7
--- /dev/null
+++ b/examples/chatroom/app.py
@@ -0,0 +1,102 @@
+import asyncio
+import websockets
+import multiprocessing
+from MicroPie import Server
+from gunicorn.app.wsgiapp import run as gunicorn_run
+
+# Store connected WebSocket clients
+connected_clients = set()
+
+class MyApp(Server):
+    def index(self):
+        return """
+        <html>
+        <head>
+            <script>
+                var ws = new WebSocket("ws://localhost:8765");
+                ws.onopen = function() {
+                    console.log("Connected to WebSocket server");
+                };
+                ws.onmessage = function(event) {
+                    document.getElementById("output").innerHTML += event.data + "<br>";
+                };
+                function sendMessage() {
+                    var message = document.getElementById("message").value;
+                    ws.send(message);
+                    document.getElementById("message").value = "";  // Clear input after sending
+                }
+                window.onbeforeunload = function() {
+                    ws.close();
+                };
+            </script>
+        </head>
+        <body>
+            <h1>WebSocket Chat</h1>
+            <input type="text" id="message" placeholder="Type a message">
+            <button onclick="sendMessage()">Send</button>
+            <div id="output"></div>
+        </body>
+        </html>
+        """
+
+async def websocket_handler(websocket):
+    """Handles incoming WebSocket connections and broadcasts messages to all clients."""
+    global connected_clients
+    connected_clients.add(websocket)
+    print("Client connected")
+
+    try:
+        async for message in websocket:
+            print(f"Received: {message}")
+            response = f"User: {message}"
+            await broadcast(response)  # Send to all connected clients
+    except websockets.exceptions.ConnectionClosed:
+        print("Client disconnected")
+    finally:
+        connected_clients.remove(websocket)
+
+async def broadcast(message):
+    """Send a message to all connected WebSocket clients."""
+    if connected_clients:
+        await asyncio.wait([client.send(message) for client in connected_clients])
+
+async def websocket_server():
+    """Start the WebSocket server within the asyncio event loop."""
+    async with websockets.serve(websocket_handler, "localhost", 8765):
+        print("WebSocket server started on ws://localhost:8765")
+        await asyncio.Future()  # Keep the server running indefinitely
+
+def start_websocket_server():
+    """Runs the WebSocket server with asyncio.run() in a separate thread."""
+    asyncio.run(websocket_server())
+
+def start_gunicorn_server():
+    """Starts the Gunicorn server programmatically."""
+    import sys
+    sys.argv = [
+        "gunicorn",
+        "-w", "4",  # Number of workers
+        "-b", "127.0.0.1:8080",  # Bind to localhost:8080
+        "app:wsgi_app"  # Module:variable format for WSGI app
+    ]
+    gunicorn_run()
+
+# Create WSGI app for Gunicorn
+app = MyApp()
+wsgi_app = app.wsgi_app
+
+if __name__ == "__main__":
+    import threading
+
+    # Start the WebSocket server in a separate thread
+    ws_thread = threading.Thread(target=start_websocket_server, daemon=True)
+    ws_thread.start()
+
+    print("WebSocket server running on ws://localhost:8765")
+
+    # Start the Gunicorn server in a separate process
+    gunicorn_process = multiprocessing.Process(target=start_gunicorn_server)
+    gunicorn_process.start()
+
+    gunicorn_process.join()  # Keep the main process alive
+
diff --git a/examples/websockets-chat/app.py b/examples/websockets-chat/app.py
deleted file mode 100644
index 0be7dba..0000000
--- a/examples/websockets-chat/app.py
+++ /dev/null
@@ -1,60 +0,0 @@
-import asyncio
-import websockets
-from MicroPie import Server
-
-class MyApp(Server):
-    def index(self):
-        return """
-        <html>
-        <head>
-            <script>
-                var ws = new WebSocket("ws://localhost:8765");
-                ws.onmessage = function(event) {
-                    document.getElementById("output").innerHTML += event.data + "<br>";
-                };
-                function sendMessage() {
-                    var message = document.getElementById("message").value;
-                    ws.send(message);
-                }
-            </script>
-        </head>
-        <body>
-            <h1>WebSocket Chat</h1>
-            <input type="text" id="message" placeholder="Type a message">
-            <button onclick="sendMessage()">Send</button>
-            <div id="output"></div>
-        </body>
-        </html>
-        """
-
-async def websocket_handler(websocket):
-    """Handles incoming WebSocket connections"""
-    print("Client connected")
-    try:
-        async for message in websocket:
-            print(f"Received: {message}")
-            response = f"Echo: {message}"
-            await websocket.send(response)
-    except websockets.exceptions.ConnectionClosed:
-        print("Client disconnected")
-
-async def websocket_server():
-    """Start WebSocket server within the asyncio event loop"""
-    async with websockets.serve(websocket_handler, "localhost", 8765):
-        print("WebSocket server started on ws://localhost:8765")
-        await asyncio.Future()  # Keep the server running indefinitely
-
-def start_websocket_server():
-    """Runs the WebSocket server with asyncio.run() in a separate thread"""
-    asyncio.run(websocket_server())
-
-if __name__ == "__main__":
-    import threading
-
-    # Start the WebSocket server in a separate thread
-    ws_thread = threading.Thread(target=start_websocket_server, daemon=True)
-    ws_thread.start()
-
-    # Start the MicroPie server
-    MyApp().run()
-