#!/usr/bin/env python3
"""
A simple asynchronous web server using aiohttp.
Features:
- Handles GET requests on '/' with a plain text response.
- Handles GET requests on '/json' with a JSON response.
- Handles GET requests on '/async-work' with simulated async work (sleeps for 1 second).
- Supports concurrent requests efficiently due to asyncio.
Installation:
pip install aiohttp
Run:
python server.py
Visit: http://localhost:8080/
"""
from aiohttp import web
import asyncio
import json
async def hello(request):
"""Basic hello world endpoint."""
return web.Response(text="Hello, asynchronous world! 🚀")
async def json_response(request):
"""Returns a JSON response."""
data = {
"message": "This is an async JSON response",
"timestamp": asyncio.get_event_loop().time()
}
return web.json_response(data, status=200)
async def async_work(request):
"""Simulates async work (e.g., database query or I/O)."""
await asyncio.sleep(1) # Simulate 1 second of async work
return web.Response(text="Async work completed after 1 second! ⏱️")
async def health_check(request):
"""Simple health check endpoint."""
return web.json_response({"status": "healthy", "uptime": "always"})
def init_app():
"""Initialize the aiohttp application."""
app = web.Application()
# Add routes
app.router.add_get('/', hello)
app.router.add_get('/json', json_response)
app.router.add_get('/async', async_work)
app.router.add_get('/health', health_check)
# Optional: Add middleware for logging
async def log_middleware(app, handler):
async def middleware_handler(request):
print(f"Request: {request.method} {request.path}")
response = await handler(request)
print(f"Response: {response.status}")
return response
return middleware_handler
app.middlewares.append(log_middleware)
return app
async def main():
"""Run the server."""
app = init_app()
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, 'localhost', 8080)
await site.start()
print("Server starting on http://localhost:8080")
print("Press Ctrl+C to stop.")
try:
await asyncio.Future() # Run forever
finally:
await runner.cleanup()
if __name__ == '__main__':
asyncio.run(main())
How to Run
- Install dependencies:
pip install aiohttp
- Save the code to
server.py.
- Run:
python server.py
- Open your browser or use
curl:
curl http://localhost:8080/ → "Hello, asynchronous world! 🚀"
curl http://localhost:8080/json → JSON response
curl http://localhost:8080/async → Waits 1s, then responds (try multiple in parallel!)
curl http://localhost:8080/health → Health check
Key Async Features
- Non-blocking handlers: All routes are
async def, leveraging asyncio.
- Concurrent handling: Open multiple tabs/connections to
/async; it won't block others.
- Modern runner: Uses
AppRunner + TCPSite for production-like setup (site-specific binding).
- Middleware: Logs requests/responses asynchronously.
This scales well for I/O-bound tasks (e.g., databases via aiopg, APIs). For CPU-bound, use asyncio.to_thread(). Extend with static files, WebSockets (app.router.add_websocket()), or auth! 🔍