patx/micropie
Added ASGI support.
Commit 69b80be · patx · 01/28/2025 at 1:24AM
Comments
No comments yet.
Diff
diff --git a/MicroPie.py b/MicroPie.py
index 048adcd..ce51ae4 100644
--- a/MicroPie.py
+++ b/MicroPie.py
@@ -39,6 +39,7 @@ import os
import mimetypes
from urllib.parse import parse_qs
from typing import Optional, Dict, Any, Union, Tuple, List
+import asyncio
try:
from jinja2 import Environment, FileSystemLoader
@@ -384,3 +385,356 @@ class Server:
self.body_params[name].append(value)
else:
self.body_params[name] = [value]
+
+class AsyncServer:
+ SESSION_TIMEOUT: int = 8 * 3600 # 8 hours
+
+ def __init__(self) -> None:
+ if JINJA_INSTALLED:
+ self.env = Environment(loader=FileSystemLoader("templates"))
+
+ self.sessions: Dict[str, Dict[str, Any]] = {}
+ self.query_params: Dict[str, List[str]] = {}
+ self.body_params: Dict[str, List[str]] = {}
+ self.path_params: List[str] = []
+ self.session: Dict[str, Any] = {}
+ self.files: Dict[str, Any] = {}
+
+ async def __call__(self, scope, receive, send):
+ await self.asgi_app(scope, receive, send)
+
+ async def asgi_app(self, scope: Dict[str, Any], receive: Any, send: Any) -> None:
+ """ASGI application entrypoint for both HTTP and WebSockets."""
+
+ if scope["type"] == "websocket":
+ # Example approach for route-based WebSocket handler lookup:
+ path = scope["path"].lstrip("/")
+ path_parts = path.split("/") if path else []
+ func_name = path_parts[0] if path_parts else "default"
+ self.path_params = path_parts[1:] if len(path_parts) > 1 else []
+
+ # Use a naming convention such as websocket_<func_name>.
+ ws_handler_name = f"websocket_{func_name}"
+ handler_function = getattr(self, ws_handler_name, None)
+
+ if not handler_function:
+ await self._websocket_default(scope, receive, send)
+ return
+
+ try:
+ await handler_function(scope, receive, send)
+ except Exception:
+ await send({"type": "websocket.close", "code": 1011})
+ return
+
+ elif scope["type"] == "http":
+ method = scope["method"]
+ path = scope["path"].lstrip("/")
+ path_parts = path.split("/") if path else []
+ func_name = path_parts[0] if path_parts else "index"
+ self.path_params = path_parts[1:] if len(path_parts) > 1 else []
+
+ handler_function = getattr(self, func_name, None)
+ if not handler_function:
+ self.path_params = path_parts
+ handler_function = getattr(self, "index", None)
+
+ raw_query = scope.get("query_string", b"")
+ self.query_params = parse_qs(raw_query.decode("utf-8", "ignore"))
+
+ headers_dict = {
+ k.decode("latin-1").lower(): v.decode("latin-1")
+ for k, v in scope.get("headers", [])
+ }
+ cookies = self._parse_cookies(headers_dict.get("cookie", ""))
+
+ session_id = cookies.get("session_id")
+ if session_id and session_id in self.sessions:
+ self.session = self.sessions[session_id]
+ self.session["last_access"] = time.time()
+ else:
+ session_id = str(uuid.uuid4())
+ self.session = {"last_access": time.time()}
+ self.sessions[session_id] = self.session
+
+ self.body_params = {}
+ self.files = {}
+ if method in ("POST", "PUT", "PATCH"):
+ body_data = bytearray()
+ while True:
+ msg = await receive()
+ if msg["type"] == "http.request":
+ body_data += msg.get("body", b"")
+ if not msg.get("more_body"):
+ break
+ content_type = headers_dict.get("content-type", "")
+ if "multipart/form-data" in content_type:
+ self.parse_multipart(bytes(body_data), content_type)
+ else:
+ body_str = body_data.decode("utf-8", "ignore")
+ self.body_params = parse_qs(body_str)
+
+ sig = inspect.signature(handler_function)
+ func_args = []
+ for param in sig.parameters.values():
+ if self.path_params:
+ func_args.append(self.path_params.pop(0))
+ elif param.name in self.query_params:
+ func_args.append(self.query_params[param.name][0])
+ elif param.name in self.body_params:
+ func_args.append(self.body_params[param.name][0])
+ elif param.name in self.files:
+ func_args.append(self.files[param.name])
+ elif param.name in self.session:
+ func_args.append(self.session[param.name])
+ elif param.default is not param.empty:
+ func_args.append(param.default)
+ else:
+ await self._send_response(
+ send,
+ status_code=400,
+ body=f"400 Bad Request: Missing required parameter '{param.name}'",
+ )
+ return
+
+ if handler_function == getattr(self, "index", None) and not func_args and path:
+ await self._send_response(send, status_code=404, body="404 Not Found")
+ return
+
+ try:
+ if inspect.iscoroutinefunction(handler_function):
+ result = await handler_function(*func_args)
+ else:
+ result = handler_function(*func_args)
+ except Exception as e:
+ print(f"Error processing request: {e}")
+ await self._send_response(
+ send, status_code=500, body="500 Internal Server Error"
+ )
+ return
+
+ status_code = 200
+ response_body = result
+ extra_headers: List[Tuple[str, str]] = []
+
+ if isinstance(result, tuple):
+ if len(result) == 2:
+ status_code, response_body = result
+ elif len(result) == 3:
+ status_code, response_body, extra_headers = result
+ else:
+ await self._send_response(
+ send, status_code=500,
+ body="500 Internal Server Error: Invalid response tuple"
+ )
+ return
+
+ session_cookie_header = (
+ "Set-Cookie",
+ f"session_id={session_id}; Path=/; HttpOnly; SameSite=Strict"
+ )
+ has_session_cookie = any(
+ h[0].lower() == "set-cookie" and "session_id=" in h[1]
+ for h in extra_headers
+ )
+ if not has_session_cookie:
+ extra_headers.append(session_cookie_header)
+
+ await self._send_response(
+ send,
+ status_code=status_code,
+ body=response_body,
+ extra_headers=extra_headers
+ )
+
+ async def _websocket_default(self, scope: Dict[str, Any], receive: Any, send: Any):
+ """Default WebSocket handler if no match is found."""
+ await send({"type": "websocket.accept"})
+ await send({"type": "websocket.close", "code": 1000})
+
+ def _parse_cookies(self, cookie_header: str) -> Dict[str, str]:
+ cookies: Dict[str, str] = {}
+ if not cookie_header:
+ return cookies
+ for cookie in cookie_header.split(";"):
+ if "=" in cookie:
+ k, v = cookie.strip().split("=", 1)
+ cookies[k] = v
+ return cookies
+
+ def parse_multipart(self, body: bytes, content_type: str) -> None:
+ boundary = None
+ parts = content_type.split(";")
+ for part in parts:
+ part = part.strip()
+ if part.startswith("boundary="):
+ boundary = part.split("=", 1)[1]
+ break
+
+ if not boundary:
+ raise ValueError("Boundary not found in Content-Type header.")
+
+ boundary_bytes = boundary.encode("utf-8")
+ delimiter = b"--" + boundary_bytes
+ sections = body.split(delimiter)
+ for section in sections:
+ if not section or section in (b"--", b"--\r\n"):
+ continue
+ if section.startswith(b"\r\n"):
+ section = section[2:]
+ if section.endswith(b"\r\n"):
+ section = section[:-2]
+ if section == b"--":
+ continue
+
+ try:
+ headers, content = section.split(b"\r\n\r\n", 1)
+ except ValueError:
+ continue
+
+ headers_list = headers.decode("utf-8", "ignore").split("\r\n")
+ header_dict = {}
+ for header_line in headers_list:
+ if ":" in header_line:
+ key, value = header_line.split(":", 1)
+ header_dict[key.strip().lower()] = value.strip()
+
+ disposition = header_dict.get("content-disposition", "")
+ disposition_parts = disposition.split(";")
+ disposition_dict = {}
+ for disp_part in disposition_parts:
+ if "=" in disp_part:
+ k, v = disp_part.strip().split("=", 1)
+ disposition_dict[k] = v.strip('"')
+
+ name = disposition_dict.get("name")
+ filename = disposition_dict.get("filename")
+
+ if filename:
+ file_content_type = header_dict.get("content-type", "application/octet-stream")
+ self.files[name] = {
+ "filename": filename,
+ "content_type": file_content_type,
+ "data": content
+ }
+ elif name:
+ value = content.decode("utf-8", "ignore")
+ if name in self.body_params:
+ self.body_params[name].append(value)
+ else:
+ self.body_params[name] = [value]
+
+ async def _send_response(
+ self,
+ send: Any,
+ status_code: int,
+ body: Union[str, bytes, Any],
+ extra_headers: List[Tuple[str, str]] = None
+ ) -> None:
+ if extra_headers is None:
+ extra_headers = []
+
+ status_map = {
+ 200: "200 OK",
+ 206: "206 Partial Content",
+ 302: "302 Found",
+ 403: "403 Forbidden",
+ 404: "404 Not Found",
+ 500: "500 Internal Server Error",
+ }
+ status_text = status_map.get(status_code, f"{status_code} OK")
+
+ has_content_type = any(h[0].lower() == "content-type" for h in extra_headers)
+ if not has_content_type:
+ extra_headers.append(("Content-Type", "text/html; charset=utf-8"))
+
+ await send({
+ "type": "http.response.start",
+ "status": status_code,
+ "headers": [
+ (k.encode("latin-1"), v.encode("latin-1")) for k, v in extra_headers
+ ],
+ })
+
+ response_body = b""
+ if hasattr(body, "__iter__") and not isinstance(body, (bytes, str)):
+ for chunk in body:
+ if isinstance(chunk, str):
+ response_body += chunk.encode("utf-8")
+ else:
+ response_body += chunk
+ else:
+ if isinstance(body, str):
+ response_body = body.encode("utf-8")
+ elif isinstance(body, bytes):
+ response_body = body
+ else:
+ response_body = str(body).encode("utf-8")
+
+ await send({
+ "type": "http.response.body",
+ "body": response_body,
+ "more_body": False,
+ })
+
+ def cleanup_sessions(self) -> None:
+ now = time.time()
+ self.sessions = {
+ sid: data
+ for sid, data in self.sessions.items()
+ if data.get("last_access", now) + self.SESSION_TIMEOUT > now
+ }
+
+ def redirect(self, location: str) -> Tuple[int, str]:
+ return (
+ 302,
+ (
+ "<html><head>"
+ f"<meta http-equiv='refresh' content='0;url={location}'>"
+ "</head></html>"
+ ),
+ )
+
+ def render_template(self, name: str, **kwargs: Any) -> str:
+ if not JINJA_INSTALLED:
+ raise ImportError("Jinja2 is not installed.")
+ return self.env.get_template(name).render(kwargs)
+
+ def serve_static(
+ self, filepath: str
+ ) -> Union[Tuple[int, str], Tuple[int, bytes, List[Tuple[str, str]]]]:
+ safe_root = os.path.abspath("static")
+ requested_file = os.path.abspath(os.path.join("static", filepath))
+ if not requested_file.startswith(safe_root):
+ return 403, "403 Forbidden"
+ if not os.path.isfile(requested_file):
+ return 404, "404 Not Found"
+ content_type, _ = mimetypes.guess_type(requested_file)
+ if not content_type:
+ content_type = "application/octet-stream"
+ with open(requested_file, "rb") as f:
+ content = f.read()
+ return 200, content, [("Content-Type", content_type)]
+
+ def validate_request(self, method: str) -> bool:
+ try:
+ if method == "GET":
+ for key, value in self.query_params.items():
+ if (
+ not isinstance(key, str)
+ or not all(isinstance(v, str) for v in value)
+ ):
+ return False
+
+ if method == "POST":
+ for key, value in self.body_params.items():
+ if (
+ not isinstance(key, str)
+ or not all(isinstance(v, str) for v in value)
+ ):
+ return False
+
+ return True
+ except:
+ return False
+
diff --git a/examples/AsyncServer/HelloWorld/app.py b/examples/AsyncServer/HelloWorld/app.py
new file mode 100644
index 0000000..ba5a603
--- /dev/null
+++ b/examples/AsyncServer/HelloWorld/app.py
@@ -0,0 +1,12 @@
+from MicroPie import AsyncServer
+
+
+class Root(AsyncServer):
+
+ async def index(self):
+ return 'Hello ASGI World!'
+
+ async def hello(self, name="ASGI"):
+ return f'Hello {name}!'
+
+app = Root() # Run with `uvicorn app:app`
diff --git a/examples/AsyncServer/WebcamStream/app.py b/examples/AsyncServer/WebcamStream/app.py
new file mode 100644
index 0000000..5db817d
--- /dev/null
+++ b/examples/AsyncServer/WebcamStream/app.py
@@ -0,0 +1,173 @@
+import uvicorn
+from typing import Dict, Set, Any
+
+from MicroPie import AsyncServer
+
+# Keep track of active users (who have "started streaming")
+active_users = set()
+
+# A simple in-memory registry of connected WebSocket clients:
+# For each username, we store sets of WebSocket connections:
+streamers: Dict[str, Set[Any]] = {}
+watchers: Dict[str, Set[Any]] = {}
+
+
+class MyApp(AsyncServer):
+
+ async def index(self):
+ """Show the home page with form to either start or watch stream."""
+ return self.render_template("index.html")
+
+ async def submit(self, username, action):
+ """
+ Handle the form submission from 'index.html'.
+ Allows user to pick 'Start Streaming' or 'Watch Stream'.
+ """
+ if username:
+ active_users.add(username)
+ if action == "Start Streaming":
+ return self.redirect(f"/stream/{username}")
+ elif action == "Watch Stream":
+ return self.redirect(f"/watch/{username}")
+ return self.redirect("/")
+
+ async def stream(self, username):
+ """
+ Show the streaming page for a particular username.
+ Only valid if the username is in active_users.
+ """
+ if username not in active_users:
+ return self.redirect("/")
+ return self.render_template("stream.html", username=username)
+
+ async def watch(self, username):
+ """
+ Show the watch page for a particular username.
+ Only valid if the username is in active_users.
+ """
+ if username not in active_users:
+ return self.redirect("/")
+ return self.render_template("watch.html", username=username)
+
+ #
+ # WebSocket routes
+ #
+ async def websocket_stream(self, scope, receive, send):
+ """
+ Handle WebSocket connections for a streamer, i.e. /stream/<username>.
+ Path params: [username]
+ """
+ # We expect self.path_params[0] to be the username.
+ if not self.path_params:
+ await self._reject_websocket(send)
+ return
+
+ username = self.path_params[0]
+ if username not in active_users:
+ await self._reject_websocket(send)
+ return
+
+ # Accept the WebSocket connection
+ await send({"type": "websocket.accept"})
+
+ # Ensure we have a set for this username
+ if username not in streamers:
+ streamers[username] = set()
+ streamers[username].add(send)
+
+ try:
+ while True:
+ message = await receive()
+ if message["type"] == "websocket.receive":
+ # We expect JSON or text frames. If binary, adapt as needed.
+ # For a simple approach, let's assume 'text' with a JSON-like structure
+ # or a raw image frame in 'bytes'.
+ if "text" in message:
+ text_data = message["text"]
+ # Broadcast text_data to watchers of this username
+ await self._broadcast(username, text_data)
+ elif "bytes" in message:
+ binary_frame = message["bytes"]
+ # Broadcast binary frame to watchers of this username
+ await self._broadcast(username, binary_frame, is_binary=True)
+ elif message["type"] == "websocket.disconnect":
+ break
+ finally:
+ # On disconnect, remove this send channel from the streamer set
+ streamers[username].discard(send)
+ if not streamers[username]:
+ del streamers[username]
+
+ async def websocket_watch(self, scope, receive, send):
+ """
+ Handle WebSocket connections for watchers, i.e. /watch/<username>.
+ Path params: [username]
+ """
+ # We expect self.path_params[0] to be the username.
+ if not self.path_params:
+ await self._reject_websocket(send)
+ return
+
+ username = self.path_params[0]
+ if username not in active_users:
+ await self._reject_websocket(send)
+ return
+
+ # Accept the WebSocket connection
+ await send({"type": "websocket.accept"})
+
+ # Ensure we have a set for watchers of this username
+ if username not in watchers:
+ watchers[username] = set()
+ watchers[username].add(send)
+
+ try:
+ while True:
+ message = await receive()
+ # Typically watchers won't send frames, but you could handle
+ # text commands from watchers if needed.
+ if message["type"] == "websocket.disconnect":
+ break
+ finally:
+ # On disconnect, remove this send channel from the watchers set
+ watchers[username].discard(send)
+ if not watchers[username]:
+ del watchers[username]
+
+ #
+ # Helper methods
+ #
+ async def _reject_websocket(self, send):
+ """Reject a WebSocket connection (invalid user or path)."""
+ await send({"type": "websocket.accept"})
+ await send({"type": "websocket.close", "code": 4000})
+
+ async def _broadcast(self, username: str, data, is_binary: bool = False):
+ """
+ Broadcast a message to all watchers of the specified username.
+ data can be str or bytes. is_binary toggles send mode.
+ """
+ if username not in watchers:
+ return
+ for ws_send in list(watchers[username]):
+ try:
+ if is_binary:
+ await ws_send({"type": "websocket.send", "bytes": data})
+ else:
+ await ws_send({"type": "websocket.send", "text": data})
+ except:
+ # If we fail to send, assume the connection is dead
+ watchers[username].discard(ws_send)
+ if not watchers[username]:
+ del watchers[username]
+
+
+# Create our application instance
+app = MyApp()
+
+#
+# If you want to run directly from python (instead of `uvicorn myapp:app`), do:
+#
+if __name__ == "__main__":
+ uvicorn.run("myapp:app", host="0.0.0.0", port=5000, reload=True)
+
diff --git a/examples/streaming/templates/index.html b/examples/AsyncServer/WebcamStream/templates/index.html
similarity index 100%
rename from examples/streaming/templates/index.html
rename to examples/AsyncServer/WebcamStream/templates/index.html
diff --git a/examples/AsyncServer/WebcamStream/templates/stream.html b/examples/AsyncServer/WebcamStream/templates/stream.html
new file mode 100644
index 0000000..b48da16
--- /dev/null
+++ b/examples/AsyncServer/WebcamStream/templates/stream.html
@@ -0,0 +1,64 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
+ <title>Streaming: {{ username }}</title>
+</head>
+<body>
+ <h1>Streaming as {{ username }}</h1>
+ <video id="webcam" autoplay playsinline></video>
+
+ <script>
+ const username = "{{ username }}";
+
+ // Create a WebSocket to your /stream/<username> route
+ const ws = new WebSocket(`ws://${window.location.host}/stream/${username}`);
+
+ // Wait for the connection to open
+ ws.onopen = function () {
+ console.log("Connected as streamer for", username);
+ startWebcam();
+ };
+
+ ws.onclose = function () {
+ console.log("WebSocket closed");
+ };
+
+ async function startWebcam() {
+ try {
+ // Capture the user's webcam
+ const stream = await navigator.mediaDevices.getUserMedia({ video: true });
+ const videoElement = document.getElementById('webcam');
+ videoElement.srcObject = stream;
+
+ // Create an offscreen canvas to grab frames
+ const canvas = document.createElement('canvas');
+ const context = canvas.getContext('2d');
+
+ // Adjust canvas size to match the video (or choose your own)
+ const [track] = stream.getVideoTracks();
+ const settings = track.getSettings();
+ canvas.width = settings.width || 640;
+ canvas.height = settings.height || 480;
+
+ setInterval(() => {
+ // Draw the current video frame to the canvas
+ context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
+
+ // Convert to base64-encoded image (data URL)
+ const frameDataUrl = canvas.toDataURL('image/webp');
+
+ // Send it via the WebSocket
+ if (ws.readyState === WebSocket.OPEN) {
+ ws.send(frameDataUrl);
+ }
+ }, 100); // ~10 FPS
+ } catch (err) {
+ console.error("Error accessing webcam:", err);
+ }
+ }
+ </script>
+</body>
+</html>
+
diff --git a/examples/AsyncServer/WebcamStream/templates/watch.html b/examples/AsyncServer/WebcamStream/templates/watch.html
new file mode 100644
index 0000000..007cf77
--- /dev/null
+++ b/examples/AsyncServer/WebcamStream/templates/watch.html
@@ -0,0 +1,35 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
+ <title>Watching: {{ username }}</title>
+</head>
+<body>
+ <h1>Watching Stream of {{ username }}</h1>
+ <img id="videoFeed" style="width: 100%; max-width: 800px;" />
+
+ <script>
+ const username = "{{ username }}";
+
+ // Create a WebSocket to your /watch/<username> route
+ const ws = new WebSocket(`ws://${window.location.host}/watch/${username}`);
+
+ // Called when the WebSocket connection is established
+ ws.onopen = function () {
+ console.log("Connected as watcher for", username);
+ };
+
+ // Called whenever the server broadcasts a new frame
+ ws.onmessage = function (event) {
+ // Here, event.data is expected to be a dataURL or other string
+ document.getElementById("videoFeed").src = event.data;
+ };
+
+ // Called when the WebSocket is closed (e.g., streamer goes offline)
+ ws.onclose = function () {
+ console.log("WebSocket closed");
+ };
+ </script>
+</body>
+</html>
diff --git a/examples/file_uploads/app.py b/examples/Server/file_uploads/app.py
similarity index 92%
rename from examples/file_uploads/app.py
rename to examples/Server/file_uploads/app.py
index afd4cd6..ff094f0 100644
--- a/examples/file_uploads/app.py
+++ b/examples/Server/file_uploads/app.py
@@ -1,6 +1,7 @@
from MicroPie import Server
import os, uuid
+
class Root(Server):
def upload_file(self, file):
@@ -55,4 +56,9 @@ class Root(Server):
"</html>"
)
-Root().run()
+
+
+app = Root()
+wsgi_app = app.wsgi_app # Run with `gunicorn app:wsgi_app`
+if __name__ == "__main__":
+ app.run() # Run with `python3 app.py`
diff --git a/examples/headers/app.py b/examples/Server/headers/app.py
similarity index 82%
rename from examples/headers/app.py
rename to examples/Server/headers/app.py
index ccc3811..4746d1d 100644
--- a/examples/headers/app.py
+++ b/examples/Server/headers/app.py
@@ -1,5 +1,6 @@
from MicroPie import Server
+
class Root(Server):
def index(self):
headers = [
@@ -12,8 +13,9 @@ class Root(Server):
]
return 200, "hello world", headers
-app = Root()
-wsgi_app = app.wsgi_app
+
+app = Root()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
if __name__ == "__main__":
- app.run()
+ app.run() # Run with `python3 app.py`
diff --git a/examples/pastebin/app.py b/examples/Server/pastebin/app.py
similarity index 84%
rename from examples/pastebin/app.py
rename to examples/Server/pastebin/app.py
index ba6e8a2..beb68c3 100644
--- a/examples/pastebin/app.py
+++ b/examples/Server/pastebin/app.py
@@ -33,12 +33,8 @@ class Root(Server):
paste_content=db.get(paste_id))
-# Create a instance of our MicroPie App
-app = Root()
-
-# Run with `gunicorn app:wsgi_app`
-wsgi_app = app.wsgi_app
-# Run with `python3 app.py`
-if __name__ == '__main__':
- app.run()
+app = Root()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
+if __name__ == "__main__":
+ app.run() # Run with `python3 app.py`
diff --git a/examples/pastebin/templates/index.html b/examples/Server/pastebin/templates/index.html
similarity index 100%
rename from examples/pastebin/templates/index.html
rename to examples/Server/pastebin/templates/index.html
diff --git a/examples/pastebin/templates/paste.html b/examples/Server/pastebin/templates/paste.html
similarity index 100%
rename from examples/pastebin/templates/paste.html
rename to examples/Server/pastebin/templates/paste.html
diff --git a/examples/requests/app.py b/examples/Server/requests/app.py
similarity index 92%
rename from examples/requests/app.py
rename to examples/Server/requests/app.py
index 5ca8baf..23e6d31 100644
--- a/examples/requests/app.py
+++ b/examples/Server/requests/app.py
@@ -28,7 +28,7 @@ def options_handler():
]
# Define the custom server application
-class MyApp(Server):
+class Root(Server):
# Handle root URL requests and delegate based on HTTP method
def index(self):
@@ -61,8 +61,9 @@ class MyApp(Server):
# 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()
+
+app = Root()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
+if __name__ == "__main__":
+ app.run() # Run with `python3 app.py`
diff --git a/examples/todolist/app.py b/examples/Server/todolist/app.py
similarity index 97%
rename from examples/todolist/app.py
rename to examples/Server/todolist/app.py
index fbd8ccc..6fa82b5 100644
--- a/examples/todolist/app.py
+++ b/examples/Server/todolist/app.py
@@ -48,7 +48,7 @@ def delete_item(item_id):
# ToDoApp Class
# ----------------------------------------------------------------------------
-class ToDoApp(Server):
+class Root(Server):
"""Our ToDo application, based on the MicroPie Server."""
users = {"username": "password"} # Simple user store
@@ -137,11 +137,7 @@ class ToDoApp(Server):
# Main
# ----------------------------------------------------------------------------
-app = ToDoApp()
-
-wsgi_app = app.wsgi_app
-
+app = Root()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
if __name__ == "__main__":
- app.run()
-
-
+ app.run() # Run with `python3 app.py`
diff --git a/examples/todolist/templates/index.html b/examples/Server/todolist/templates/index.html
similarity index 100%
rename from examples/todolist/templates/index.html
rename to examples/Server/todolist/templates/index.html
diff --git a/examples/todolist/templates/login.html b/examples/Server/todolist/templates/login.html
similarity index 100%
rename from examples/todolist/templates/login.html
rename to examples/Server/todolist/templates/login.html
diff --git a/examples/todolist/templates/tag.html b/examples/Server/todolist/templates/tag.html
similarity index 100%
rename from examples/todolist/templates/tag.html
rename to examples/Server/todolist/templates/tag.html
diff --git a/examples/twutr/templates/layout.html b/examples/Server/twutr/templates/layout.html
similarity index 100%
rename from examples/twutr/templates/layout.html
rename to examples/Server/twutr/templates/layout.html
diff --git a/examples/twutr/templates/list_followers.html b/examples/Server/twutr/templates/list_followers.html
similarity index 100%
rename from examples/twutr/templates/list_followers.html
rename to examples/Server/twutr/templates/list_followers.html
diff --git a/examples/twutr/templates/list_following.html b/examples/Server/twutr/templates/list_following.html
similarity index 100%
rename from examples/twutr/templates/list_following.html
rename to examples/Server/twutr/templates/list_following.html
diff --git a/examples/twutr/templates/login.html b/examples/Server/twutr/templates/login.html
similarity index 100%
rename from examples/twutr/templates/login.html
rename to examples/Server/twutr/templates/login.html
diff --git a/examples/twutr/templates/public.html b/examples/Server/twutr/templates/public.html
similarity index 100%
rename from examples/twutr/templates/public.html
rename to examples/Server/twutr/templates/public.html
diff --git a/examples/twutr/templates/register.html b/examples/Server/twutr/templates/register.html
similarity index 100%
rename from examples/twutr/templates/register.html
rename to examples/Server/twutr/templates/register.html
diff --git a/examples/twutr/templates/timeline.html b/examples/Server/twutr/templates/timeline.html
similarity index 100%
rename from examples/twutr/templates/timeline.html
rename to examples/Server/twutr/templates/timeline.html
diff --git a/examples/twutr/templates/user.html b/examples/Server/twutr/templates/user.html
similarity index 100%
rename from examples/twutr/templates/user.html
rename to examples/Server/twutr/templates/user.html
diff --git a/examples/twutr/twutr.py b/examples/Server/twutr/twutr.py
similarity index 99%
rename from examples/twutr/twutr.py
rename to examples/Server/twutr/twutr.py
index 83a71da..4706ae1 100644
--- a/examples/twutr/twutr.py
+++ b/examples/Server/twutr/twutr.py
@@ -333,9 +333,9 @@ class Twutr(Server):
self.session.clear()
return self.redirect('/public')
-app = Twutr()
-wsgi_app = app.wsgi_app
-if __name__ == "__main__":
- app.run()
+app = Twutr()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
+if __name__ == "__main__":
+ app.run() # Run with `python3 twutr.py`
diff --git a/examples/chatroom/app.py b/examples/Server/wsgi_streaming/chatroom.py
similarity index 98%
rename from examples/chatroom/app.py
rename to examples/Server/wsgi_streaming/chatroom.py
index 7c3948c..5c7b13b 100644
--- a/examples/chatroom/app.py
+++ b/examples/Server/wsgi_streaming/chatroom.py
@@ -69,10 +69,8 @@ def start_websocket_server():
"""Runs the WebSocket server with asyncio.run() in a separate thread."""
asyncio.run(websocket_server())
-# Create WSGI app for Gunicorn
app = MyApp()
-wsgi_app = app.wsgi_app
if __name__ == "__main__":
import threading
diff --git a/examples/streaming/livestream.py b/examples/Server/wsgi_streaming/livestream.py
similarity index 100%
rename from examples/streaming/livestream.py
rename to examples/Server/wsgi_streaming/livestream.py
diff --git a/examples/Server/wsgi_streaming/templates/index.html b/examples/Server/wsgi_streaming/templates/index.html
new file mode 100644
index 0000000..b710858
--- /dev/null
+++ b/examples/Server/wsgi_streaming/templates/index.html
@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
+ <title>Webcam Streaming</title>
+</head>
+<body>
+ <h1>Webcam Streaming App</h1>
+ <form method="post" action="/submit">
+ <input type="text" name="username" placeholder="Enter username" required>
+ <button type="submit" name="action" value="Start Streaming">Start Streaming</button>
+ <button type="submit" name="action" value="Watch Stream">Watch Stream</button>
+ </form>
+</body>
+</html>
+
diff --git a/examples/streaming/templates/stream.html b/examples/Server/wsgi_streaming/templates/stream.html
similarity index 100%
rename from examples/streaming/templates/stream.html
rename to examples/Server/wsgi_streaming/templates/stream.html
diff --git a/examples/streaming/templates/watch.html b/examples/Server/wsgi_streaming/templates/watch.html
similarity index 100%
rename from examples/streaming/templates/watch.html
rename to examples/Server/wsgi_streaming/templates/watch.html
diff --git a/examples/streaming/text.py b/examples/Server/wsgi_streaming/text.py
similarity index 77%
rename from examples/streaming/text.py
rename to examples/Server/wsgi_streaming/text.py
index 0fd7b66..1021600 100644
--- a/examples/streaming/text.py
+++ b/examples/Server/wsgi_streaming/text.py
@@ -15,5 +15,9 @@ class Root(Server):
time.sleep(1) # simulate slow processing or data generation
return generator()
+
+
app = Root()
-app.run()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
+if __name__ == "__main__":
+ app.run() # Run with `python3 text.py`
diff --git a/examples/streaming/video1.py b/examples/Server/wsgi_streaming/video1.py
similarity index 96%
rename from examples/streaming/video1.py
rename to examples/Server/wsgi_streaming/video1.py
index efd0b72..9a07db6 100644
--- a/examples/streaming/video1.py
+++ b/examples/Server/wsgi_streaming/video1.py
@@ -3,7 +3,9 @@ from MicroPie import Server
VIDEO_PATH = "video.mp4"
+
class VideoStreamer(Server):
+
def index(self):
"""Serve a simple HTML page with a video player."""
return '''
@@ -77,11 +79,10 @@ class VideoStreamer(Server):
]
return (200, generator(0, file_size), extra_headers)
-# Create your app instance
-app = VideoStreamer()
-# The WSGI entry point Gunicorn will look for
-wsgi_app = app.wsgi_app
+
+app = VideoStreamer()
+wsgi_app = app.wsgi_app # Run with `gunicorn video1:wsgi_app`
if __name__ == "__main__":
- app.run()
+ app.run() # Run with `python3 video1.py`
diff --git a/examples/streaming/video2.py b/examples/Server/wsgi_streaming/video2.py
similarity index 89%
rename from examples/streaming/video2.py
rename to examples/Server/wsgi_streaming/video2.py
index 43559cc..e0ba7e6 100644
--- a/examples/streaming/video2.py
+++ b/examples/Server/wsgi_streaming/video2.py
@@ -3,7 +3,9 @@ from MicroPie import Server
VIDEO_PATH = "video.mp4"
+
class VideoStreamer(Server):
+
def index(self):
"""Serve the HTML page with a video player."""
return '''
@@ -32,8 +34,10 @@ class VideoStreamer(Server):
return generator()
-app = VideoStreamer()
-wsgi_app = app.wsgi_app
+
+
+app = VideoStreamer()
+wsgi_app = app.wsgi_app # Run with `gunicorn text:wsgi_app`
if __name__ == "__main__":
- app.run()
+ app.run() # Run with `python3 video2.py`