python-aiohttpHow to create a server with Python Aiohttp?
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.
Helpful links
Related
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to get response code with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to download large files with Python Aiohttp?
- How to disable SSL verification in Python Aiohttp?
- How to create a connection pool with Python Aiohttp?
- How to close a Python Aiohttp session?
More of Python Aiohttp
- How to handle x-www-form-urlencoded with Python Aiohttp?
- How to reuse a session with Python Aiohttp?
- How to rate limit with Python Aiohttp?
- How to redirect with Python Aiohttp?
- How to retry a request with Python Aiohttp?
- How to create a JSON response using Python Aiohttp?
- How to create a websocket server using Python Aiohttp?
- How to set query parameters with Python Aiohttp?
- How to use HTTP2 with Python Aiohttp?
- How to close a Python Aiohttp session?
See more codes...