Masashi
Posted on December 10, 2021
Starlette, FastAPI, Quart, all are web-frameworks, (backend), but, they all have one more thing in common. They are based on ASGI.
In PEP-333, WGSI was introduced, long ago, why? To facilitate the use of any web server with any WSGI-based framework. As a result, we have Flask, Django, Pyramid and other frameworks, and WSGI servers like Gunicorn.
Why ASGI?
ASGI stands for Asynchronous Server Gateway Interface and it lets us use any ASGI web server with any ASGI-based framework.
Pretty much the same right? But, WSGI was sync and ASGI is async (obviously).
What should I do with this info?
ASGI makes it much easier to make a web framework (though you don't have to) and it works on three components. scope
, send
and recieve
.
Scope
The scope is a python-dictionary object that contains information about the connection. Such as, is it http or https or ws(websocket) or wss(ws secured) or something else.
Eg:
{
"type" : "http",
"method" : "GET",
"path" : "/api",
"query_string" : "userid=999",
"headers" : [
b"accept-encoding": b"gzip, deflate, br",
b"connection": b"keep-alive",
b"cookie": b"a=b",
],
}
No text parsing, just use it. Pretty simple.
Send
Sends a Python-dictionary object containing your response.
await send({
'type': 'http.response.start',
'status': 200,
'headers': [
b"content-type": b"text/html",
b"date" : b"Fri, 10 Dec 2021 06:16:51 GMT",
b"cache-control" : b"none",
b"set-cookie": b"a=b"
]
})
await send({
'type': 'http.response.body',
'body': b"Hello user",
})
Recieve
It is used get more info from the user after connection is established. Eg: HTTP body.
But still, where do I use these?
It all is there in an ASGI callable as arguments.
It may be a function or a class.
Eg:
async def app(scope, recieve, send):
# Some logic here
or,
class App:
# other things
async def __call__(self, scope, recieve, send):
#Some logic here
Conclusion
ASGI is used to make frameworks, but knowing it is needed for working with Starlette, and maybe other frameworks as well. It can be used for making middlewares of other frameworks as well. It can be used for other protocols. There is a variety of things to build by following this specification. This was just a brief overview. Read the full specification at asgi.readthedocs.org. If you want to see an example of application of ASGI, look at an HTTP framework named willpyre that I made, or check some well known framework like Starlette, or Sanic.
Also, check some ASGI servers like Uvicorn, Hypercorn or Daphne if you want to see how the specification is for the servers.
That was all. Hope you all stay well.
Posted on December 10, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.