Junior — Middle
Explain what ASGI is and what it is used for in modern web applications.
sobes.tech AI
Answer from AI
ASGI (Asynchronous Server Gateway Interface) is a specification for an interface between web servers and Python applications that supports asynchronous programming. Unlike WSGI, which operates synchronously, ASGI allows handling multiple requests simultaneously, supports WebSocket and other protocols requiring persistent connections.
ASGI is used in modern web applications to improve performance and scalability, especially when working with real-time data, long-lived connections, or asynchronous tasks. For example, frameworks like Starlette, FastAPI, and Django Channels use ASGI to support asynchronous operations.
Example of a simple ASGI application:
async def app(scope, receive, send):
if scope['type'] == 'http':
await send({
'type': 'http.response.start',
'status': 200,
'headers': [(b'content-type', b'text/plain')],
})
await send({
'type': 'http.response.body',
'body': b'Hello, ASGI!',
})