in

Top 9 Asynchronous Web Frameworks for Python

default image
Asynchronous Python frameworks

Asynchronous programming has become a must-have for modern web development. With users expecting near real-time experiences, synchronous frameworks that process one request at a time just don‘t cut it anymore.

Python has excellent support for asynchronous programming through its asyncio module. This has led to an explosion in asynchronous web frameworks that can handle thousands of concurrent connections with great performance.

In this guide, we‘ll explore the top 9 asynchronous web frameworks for Python in 2022 based on popularity, performance, and ease of use.

1. Sanic

Sanic is one of the most popular Python asynchronous frameworks. It is built on top of asyncio and leverages async/await syntax for simple concurrent code.

Some key features and benefits of Sanic include:

  • Fast performance – Can handle thousands of requests per second.
  • Simple APIs – APIs are clean and easy to write.
  • Async/await syntax – Uses modern async/await instead of callbacks.
  • WSGI support – Can run as a WSGI app for compatibility.
  • Pluggable – Extend with middleware and plugins.

Here is an example "hello world" API in Sanic:

from sanic import Sanic

app = Sanic()

@app.route(‘/‘)
async def test(request):
    return text(‘Hello World!‘) 

if __name__ == ‘__main__‘:
   app.run(host=‘0.0.0.0‘, port=8000)

Sanic is a great choice if you want a fast, simple framework to build APIs and microservices. The syntax is very clean and easy to pick up.

2. FastAPI

FastAPI is a modern, highly performant asynchronous framework. It uses Python type hints for validation, serialization, and documentation.

Key features of FastAPI include:

  • Fast – Leverages Starlette and Pydantic for speed.
  • Easy APIs – Designed to be easy and intuitive.
  • Automatic documentation – Auto-generates OpenAPI docs.
  • Data validation – Uses type hints for data validation.
  • Schema generation – Automatically generates JSON Schemas.

Here is an example API in FastAPI:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def root():
    return {"message": "Hello World"}

FastAPI is one of the newest async frameworks but has quickly gained popularity for its ease of use and advanced features like automatic documentation generation. It‘s a good choice for building APIs where validation and documentation are important.

3. aiohttp

aiohttp is a performant asynchronous HTTP client/server framework built on asyncio. Some key features include:

  • HTTP client/server – Can act as both a web client and web server.
  • WebSocket support – Great for real-time applications.
  • Middlewares and signals – Extendable via middlewares and signals
  • App runners – Multiple ways to run and manage your application.

Here is an example with aiohttp:

from aiohttp import web

async def handle(request):
    return web.Response(text="Hello World")

app = web.Application()
app.add_routes([web.get(‘/‘, handle)])

web.run_app(app)

aiohttp has been around for a while and is very mature and production-ready. It‘s a great choice if you need both a web client and server.

4. Tornado

Tornado is another popular asynchronous web framework that has been around for a long time. Some key features:

  • Highly scalable – Used by sites like FriendFeed and Quora to scale.
  • Non-blocking HTTP – Asynchronous HTTP client and server implementation.
  • Long polling and WebSockets – Support for real-time web.
  • Template engine – Template support using Django-style templates.

Here is an example "hello world" app with Tornado:

import tornado.web
import tornado.ioloop

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888) 
    tornado.ioloop.IOLoop.current().start()

Tornado is quite barebones but highly scalable, performant, and stable. It‘s a good choice for applications where you need scalability and speed.

5. Starlette

Starlette is an ASGI framework that is simple but powerful. Some key features:

  • ASGI – Built for the modern ASGI standard.
  • Websockets – Support for full-duplex connections.
  • GraphQL – Integrate with GraphQL endpoints easily.
  • Testing – Has a test client built-in for easy testing.
  • Minimal – Small codebase that‘s easy to understand.

Here is an example with Starlette:

from starlette.applications import Starlette
from starlette.responses import JSONResponse

app = Starlette()

@app.route(‘/json‘)
async def homepage(request):    
    return JSONResponse({‘hello‘: ‘world‘})

Starlette is simple but very fast. It‘s a good option if you want something minimal that gets out of your way.

6. Quart

Quart is an asyncio web framework that implements the Flask API. This allows using Flask extensions and patterns in async mode.

Some advantages of Quart:

  • Flask-like API – Implemented after Flask with same API.
  • Async features – Implements async and WebSockets.
  • Extensions – Can use many Flask extensions directly.
  • Familiar – Easy transition for Flask users.

Here is an example with Quart:

from quart import Quart 

app = Quart(__name__)

@app.route(‘/‘)
async def index():
  return "Hello World!"

app.run()

For Flask users wanting to go async, Quart is the obvious choice. You get the Flask API with added async capabilities.

7. BlackSheep

BlackSheep is a modern Python web framework for building WSGI, ASGI, and aiohttp apps. Some features:

  • Feature-rich API – Lots of utilities built-in.
  • Async support – Supports WSGI, ASGI, and aiohttp apps.
  • Documentation – Automatic documentation generation.
  • Modular design – Extend using components.
  • User-friendly – Made to be easy to use.

Here‘s a simple example with BlackSheep:

from blacksheep.server import Application
from blacksheep.messages import Response

app = Application()

@app.router.get("/")
async def home(request):
    return Response(text="Hello, world!")

app.serve("localhost", 8080)

BlackSheep is user-friendly and has many utilities built-in. It‘s good for building REST APIs and web services.

8. Falcon

Falcon is a minimalist ASGI framework for building high-performance web APIs, app backends, and microservices. Some key aspects:

  • High-speed – Benchmarked at being very high performance.
  • ASGI – Built for the modern ASGI standard.
  • Minimalist – Follows the "hooks and middleware" model.
  • Docs – Automatic documentation generation.
  • Batteries included – Comes with utilities built-in.

Here is a simple example with Falcon:

import falcon 

class QuoteResource:
    def on_get(self, req, resp):
        """Handles GET requests"""
        quote = get_quote()     
        resp.media = quote

api = falcon.App()
api.add_route(‘/quote‘, QuoteResource())

Falcon is fast, barebones, and perfect for building high-performance microservices and web APIs.

9. Japronto

Japronto is an interesting asynchronous web framework because it‘s implemented in C Python instead of pure Python. This gives it exceptional performance since it runs on bare metal.

Some key features of Japronto:

  • Blazing fast – Benchmarked faster than NodeJS and Go.
  • C Python implementation – Implemented in C giving it raw speed.
  • Async code – Uses async/await syntax.
  • Multi-protocol – Supports HTTP, WebSockets, and custom protocols.
  • Batteries included – Comes with router, request object, templates built-in.

Here is an example "hello world" in Japronto:

from japronto import Application


def hello(request):
    return request.Response(text=‘Hello world!‘)


app = Application()
app.router.add_route(‘/‘, hello)
app.run(debug=True)

The performance of Japronto is incredible given it runs on C Python. If you really need speed and control, it‘s worth exploring.

Honorable Mentions

There are a few more asynchronous frameworks worth mentioning:

  • UVICORN – A lightning-fast ASGI server implementation.
  • Bottle – A WSGI framework that can optionally run in async mode.
  • Bocadillo – An ASGI framework focused on being easy to use.

Conclusion

Python has awesome support for asynchronous programming through asyncio. This has led to many great asynchronous web frameworks like Sanic, FastAPI, Tornado, and others.

When choosing a framework, consider your requirements around performance, features, and ease of use. Sanic is recommended for simple but fast applications. FastAPI is great for APIs with its auto-documentation capabilities. Tornado and aiohttp are mature options if you need tried and tested frameworks.

Whichever you choose, asynchronous Python opens the door to building highly scalable, real-time web applications. Give one of these frameworks a try to see the performance benefits yourself!

AlexisKestler

Written by Alexis Kestler

A female web designer and programmer - Now is a 36-year IT professional with over 15 years of experience living in NorCal. I enjoy keeping my feet wet in the world of technology through reading, working, and researching topics that pique my interest.