Skip to content

Instantly share code, notes, and snippets.

@jjn1056
Created February 26, 2025 01:31
Show Gist options
  • Save jjn1056/a8ab879c8df1882f9da70666967d2644 to your computer and use it in GitHub Desktop.
Save jjn1056/a8ab879c8df1882f9da70666967d2644 to your computer and use it in GitHub Desktop.
import asyncio
# A simple logging middleware
class LoggingMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
# Only handle HTTP requests for this example.
if scope["type"] == "http":
print(f"[Middleware] Request received: {scope['path']}")
# Call the next app (or middleware) in the stack.
await self.app(scope, receive, send)
if scope["type"] == "http":
print("[Middleware] Request processing completed.")
# The basic ASGI app that returns a plain text response.
async def app(scope, receive, send):
if scope["type"] == "http":
# Start the HTTP response.
await send({
"type": "http.response.start",
"status": 200,
"headers": [
(b"content-type", b"text/plain"),
],
})
# Send the response body.
await send({
"type": "http.response.body",
"body": b"Hello, ASGI with middleware!",
})
# Wrap the app with the middleware.
app_with_middleware = LoggingMiddleware(app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment