What is ASGI (Asynchronous Server Gateway Interface)?

Elkarroumytaha
3 min readSep 30, 2022

--

Photo by Julian Hochgesang on Unsplash

Content

  • what is ASGI ?
  • How ASGI works ?
  • Implementations of ASGI ?
  • frameworks built with ASGI ?

1. what is ASGI ?

according to the official ASGI doc

ASGI (Asynchronous Server Gateway Interface) is a spiritual successor to WSGI, intended to provide a standard interface between async-capable Python web servers, frameworks, and applications.

Where WSGI provided a standard for synchronous Python apps, ASGI provides one for both asynchronous and synchronous apps, with a WSGI backwards-compatibility implementation and multiple servers and application frameworks.

NOTE : WSGI (Web Server Gateway Interface)

that means that ASGI is simply WSGI but supporting async python servers and sync servers as well ,this will affect the speed of web servers run on python and make it more powerfull

2. How ASGI works ?

ASGI act like a Gateway interface between Servers and Web applications

diagram

The ASGI interface ( or callable ) takes 3 parameters (scope, receive, send)

scope : A dictionary of information that is used to setup the state of the application , contains details about the specific connection sent (triggered) by a client

scope{
"type": "http",
"method": "GET",
"scheme": "https",
"server": ("www.example.org", 80),
"path": "/",
"headers": []
}

receive : asynchronous callable which lets the application receive event messages from the client (REQUEST)

send : asynchronous callable, that lets the application send event messages to the client (RESPONSE)

await send({
"type": "http.response.start",
"status": 200,
"headers": [
[b"content-type", b"text/plain"],
],
})
await send({
"type": "http.response.body",
"body": b"Hello, world!",
})

NOTE : Daphne and Uvicorn are web servers

3 — Implementations of ASGI ?

a simple implementation of an ASGI callable can be like :

async def application(scope, receive, send):
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
[b'content-type', b'text/plain'],
],
})

await send({
'type': 'http.response.body',
'body': b'Hello, world!',
})

You can now run the application using any ASGI server, including daphne, uvicorn

$ pip3 install uvicorn
[...]
$ uvicorn <folder>:<application> # the function to run (application in our case )
INFO: Started server process [30074]
INFO: Waiting for application startup.
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
response

4 — frameworks built with ASGI ?

there is a lot of Frameworks that built on top of this ASGI architecture , we can mention

starlette , Quart , FastApi , Django (start support ASGI from the version 3) , Asgineer , Sanic , and more …

here you can see how ASGI make python servers than ever

THANK YOU FOR BEING HERE

--

--