ctapobep / blog

My personal blog on IT topics in the form of GitHub issues.
6 stars 0 forks source link

Python WSGI/ASGI: web servers vs. middleware #12

Open ctapobep opened 2 years ago

ctapobep commented 2 years ago

WSGI (the old one) & ASGI (the new one that allows for async req handling) are low-level specs that define how App* Servers written in Python should invoke our code. So someone writes an App Server which can handle HTTP requests (parse Headers, URL, etc) and then it could invoke our function and pass all these params. Note, that there's only one function that we would supply to such App Server. So we ourselves would have to create a Dict of URL->function and do request dispatching ourselves (in Java we'd call this dispatching logic a Front Controller).

So the goal of the App Server is to work with OS-level functions for opening TCP/IP connections, reading byte inputs and writing outputs. After accepting data they put the data into more high-level objects (like a Dict) and pass it to WSGI/ASGI function. That's where our app code can take control and work with these Dicts. Examples of such App Servers: unicorn, uvicorn.

But since WSGI & ASGI are still quite low level specs, they don't usually invoke our code directly. Instead, we use what they call a Middleware. It's a library/framework which processes the low level information and does the dispatching (or whatever they were created for) in a more convenient way. Some implementations: Django, Starlette, FastAPI.

Note that Starlette is a basis for many frameworks. It has some convenient classes like Route, Request, etc. FastAPI is an even higher level framework based on Starlette - it adds integration with other libs like Pydantic and, for some inexplicable reason, SQLAcademy. It also adds what they mistakenly call a Dependency Injection, which is basically a glorified request parameter pre-processors. Python still seems to miss on a full-fledged DI.

Further readings:

*a Web Server is something that accepts HTTP requests. Nginx & Apache HTTPD and examples of Web Servers. An App Server is a Web Server which can invoke our app code.