Appearance
Using aiohttp
asyncio can achieve concurrent I/O operations in a single thread. While its power is somewhat limited on the client side, using asyncio on the server side, such as in a web server, allows for high concurrency with multiple users due to HTTP connections being I/O operations.
asyncio implements various protocols like TCP, UDP, and SSL, and aiohttp is an HTTP framework built on top of asyncio.
First, install aiohttp:
bash
$ pip install aiohttp
Next, let's write an HTTP server that handles the following URLs:
/
- Returns "Index Page"./{name}
- Returns the text "Hello, {name}!".
Here’s the code:
python
# app.py
from aiohttp import web
async def index(request):
text = "<h1>Index Page</h1>"
return web.Response(text=text, content_type="text/html")
async def hello(request):
name = request.match_info.get("name", "World")
text = f"<h1>Hello, {name}</h1>"
return web.Response(text=text, content_type="text/html")
app = web.Application()
# Add routes:
app.add_routes([web.get("/", index), web.get("/{name}", hello)])
if __name__ == "__main__":
web.run_app(app)
Run app.py
directly and visit the homepage:
Accessing http://localhost:8080/Bob
will return:
When using aiohttp, you define async functions to handle different URLs, add mappings through app.add_routes()
, and finally start the entire processing flow using run_app()
.