// plain
Creating a server with Python Aiohttp is easy and straightforward.
from aiohttp import web
async def handle(request):
name = request.match_info.get('name', "Anonymous")
text = "Hello, " + name
return web.Response(text=text)
app = web.Application()
app.add_routes([web.get('/', handle),
web.get('/{name}', handle)])
web.run_app(app)
This code will create a server that will respond to requests with a greeting.
from aiohttp import web
imports the web module from the aiohttp library.async def handle(request):
defines a function that will handle requests.name = request.match_info.get('name', "Anonymous")
gets the name parameter from the request.text = "Hello, " + name
creates a greeting string.return web.Response(text=text)
returns the greeting string as a response.app = web.Application()
creates an application instance.app.add_routes([web.get('/', handle), web.get('/{name}', handle)])
adds routes to the application.web.run_app(app)
starts the server.
group: aiohttp
onelinerhub: How to create a server with Python Aiohttp?