Get the “Top 10 Python Web Frameworks” build, which contains a version of Python and most of the tools listed in this post so you can test them out for yourself.

Python web frameworks have always been key to web development, even though Python gets a lot of kudos for its use in the Machine Learning space these days. In fact, whenever I whip up a prototype of a new idea, I usually wrap it around a web server before I test it out, or ask others to evaluate it. A web-based interface makes it far easier to interact with prototypes. In most cases, you don’t even need a GUI – a simple API served up by a web server can make your prototype just as easy to interact with.

I usually pick a quick and easy web server like Python’s Flask, but there are hundreds of web frameworks in Python. This post highlights many of the major Python web frameworks, from the old guard that have been under development for more than a decade (like Django) to newcomers on the block (like FastAPI). I’ll introduce some of the key features and functions for each framework, and also weigh the strengths and weaknesses of each.

After reading this article, you should have a good idea of what kind of projects each framework is best suited for.

Here are my top 10 Python frameworks for web development:

#1 Flask Python Web Framework

This is my “OG.” It’s my favorite Python tool, and what I always come back to when I need a simple web server fast to serve up a simple API. It features no bells or whistles (no database abstraction layer, form validations, or mail support) but does have a large set of extensions.

You can read more about how to use Flask in my previous blog post, Top 10 Python Tools to Make a Developer’s Life Easier.

Pros:

  • Simple but powerful
  • Rapid deployment – up and running in 2 seconds flat!
  • Extensibility – easily extended to cover just about any use case

Cons:

  • Not async-friendly
  • Limited “out of the box” features

#2 Bottle Python Web Framework

Bottle is very similar to Flask (in name as well!). However it aims to be a thin wrapper around a web server, and nothing more. While Flask is a micro web framework, Bottle is just a wrapper. It has useful functions like dynamic routing and templated responses, but it’s not very extensible and doesn’t scale to include pluggable modules like Flask.

However, for something really quick and dirty, it works great!

Here’s how to quickly set up and run Bottle:

from bottle import route, run
@route('/hello')
def hello():
    return "Hello World!"
run(host='localhost', port=8080, debug=True)

Pros:

  • Takes a “one file” approach best suited to simple, small projects
  • Great for quick APIs

Cons:

  • Takes a “one file” approach unsuitable for all but the smallest projects
  • Not very extensible

#3 Pyramid Python Web Framework

Pyramid is a very flexible web framework in the sense that it scales for both small and medium-sized web applications. Like Flask, it’s easy to deploy by simply importing the library into any codebase and using it as a web server. Unlike Flask, it provides a number of key features out of the box, like static asset rendering, URL generation and even a decent authentication system.

Want your application to serve as an internal tool? Pyramid is a great choice for that. Sure, it’s a little more complex than Flask, but in a good way. And it’s also well maintained, with its creators pushing regular updates.

Here’s how to quickly set up and run Pyramid:

from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response
def hello_world(request):
    return Response('Hello World!')
if __name__ == '__main__':
    with Configurator() as config:
        config.add_route('hello', '/')
        config.add_view(hello_world, route_name='hello')
        app = config.make_wsgi_app()
    server = make_server('0.0.0.0', 6543, app)
    server.serve_forever()

Pros:

  • Great set of standard features
  • The middle man between Flask and Django, where you need something more robust than Flask, but not the overkill of Django

Cons:

  • The middle man between Flask and Django, where you wish it was as simple to use as Flask, or else had more “batteries included” (ie., templating, object relational mapper, etc) like Django

#4 web2py Python Web Framework

Yes, the name isn’t very creative or attractive, but would it make sense if I told you it was created with the intention of using it for teaching?

Web2py first came into being as a teaching tool for learning about the web and web servers. It is incredibly user friendly, and even comes with its own web-based IDE jam-packed with code editor, debugger, linter and a one-click deployment tool!

Need more? Web2py comes pre-packaged with tools allowing it to run on Google App Engine and Amazon EC2 so you can deploy it in the cloud. There’s even a built-in ticketing system that automatically raises tickets whenever your web server encounters errors.

Just proves you should never judge a book by its cover! Check out the homepage and examples directory.

Pros:

  • Perfect for webdev beginners
  • Offers great support for build, deployment and even production scenarios

Cons:

  • The IDE is really just an admin console with limited code editing/debugging capabilities
  • Does not have an extensive community of web developers

#5 Falcon Python Web Framework

If speed is what you’re looking for, you’ve come to the right place. Like the name suggests, Falcon is built to be blazing fast. Its code base is optimized for handling a large number of requests.

I really love its object-oriented approach. I feel it’s more customizable than the plugin architecture that previously-discussed web frameworks bring to the table.

Falcon definitely gets the basics of buildings APIs right: it’s RESTful, fast, extensible and reliable. Organizations like LinkedIn rely on it! And its maintainers go out of the way to ensure that updates do not introduce breaking changes.

Here’s how to quickly set up and run Falcon:

import falcon
class QuoteResource:
    def on_get(self, req, resp):
        """Handles GET requests"""
        quote = {
            'quote': (
                "I've always been more interested in "
                "the future than in the past."
            ),
            'author': 'Grace Hopper'
        }
        resp.media = quote
api = falcon.API()
api.add_route('/quote', QuoteResource())

Pros

  • Did I mention the fast performance? It’s really FAST!
  • Highly customizable

Cons

  • Narrowly focused on building REST APIs
  • Backend only – not appropriate for serving front end pages

#6 FastAPI Python Web Framework

Need something that’s fast but provides more than just speed? How about automatic data validation, web sockets, and documentation? Well, that’s FastAPI for you.

It borrows a lot from the simplicity of Flask while delivering high performance that’s comparable to NodeJS or Go! Like the name suggests, it’s focused on helping you create fast APIs based on OpenAPI standards, and offers great serialization libraries.

If you’re looking to expose modules of your codebase as APIs, this is the best framework to do that. While other frameworks can render JSON structures, FastAPI was built from the bottom up with this specific task in mind.

The only thing I wish it provided is Protobuf implementations, but it’s relatively new so it may be coming in a future release.

Here’s how to quickly set up and run FastAPI:

from fastapi import FastAPI
app = FastAPI()@app.get("/")
async def root():
    return {"message": "Hello World"}

Pros

  • Among the fastest Python web frameworks
  • Async support

Cons

  • Lacks Protobuf support
  • Newer and therefore has a smaller community than other frameworks on this list

#7 Tornado Python Web Framework

Asynchronous frameworks are relatively new to Python, but with them, you can easily build large concurrent applications like real-time chat, online games, and video applications. Very much needed distractions during this era of pandemic enforced remote working!

Tornado is a Python web framework and asynchronous networking library that focuses on speed and the ability to handle large volumes of traffic. It uses non-blocking I/O to ensure exceptionally fast performance.

Over time, this framework has been gaining popularity. I would definitely recommend Tornado over Django for building real-time applications.

Here’s how to quickly set up and run Tornado:

import tornado.ioloop
import tornado.web
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()

You can see in the above example how Tornado differs from Flask. It makes the right decisions when it comes to long-standing applications, and chooses to use a non-blocking I/O to stay alive as long as it can.

Pros

  • Great support for real-time functionality
  • Fast performance

Cons

  • Lacks Object Relational Mapping (ORM)
  • Niche tool for real time apps only

#8 Sanic Python Web Framework

Want asynchronous performance but don’t like Tornado? Well you only have one other option: Sanic. Sanic is an asynchronous web framework that is built on top of uvloop, which is implemented in cython. This gives it exceptional asynchronous performance.

If you’re building anything related to routing, middleware, or sockets, Sanic should be your framework of choice. But I also like Sanic’s clean coding structure, eg.,:

-- from sanic import Sanic -- from sanic.response import json

Here’s how to quickly set up and run Sanic:

app = Sanic()
@app.route('/')
async def test(request):
    return json({'hello': 'world'})
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8000)

Pros

  • Great performance
  • Great for networking applications

Cons

  • Not as mature as other frameworks
  • Niche tool

#9 Dash Python Web Framework

Data science and machine learning have been gaining popularity with Pythonistas and enterprises alike over the past few years. In fact, it would be hard to find Python developers who haven’t at least tried out some kind of data analytics programming. But anything to do with data really needs to be coupled with a web server if you want your users to interact with and visualize it. Because data visualization is not typically the domain of a data scientist, it’s often left to seasoned web developers to step in and deliver.

But in order to expose your data model to the web, you need to know how to create both a robust backend API server and a beautiful front end UI to display your graphs. That’s a tall order for most of us, which is where Dash comes to the rescue. The Dash web platform is used extensively by data teams to produce enterprise-ready analytic apps that sit on top of Python and R models.

Dash essentially wraps graphing libraries with Python so you never need to use CSS or JavaScript in order to take advantage of them. It also has Kubernetes integration to help you seamlessly deploy and scale. The only downside is that many of its best features are behind a paywall.

Read more about Dash and how to use it in our Dash vs Bokeh blog post.

Pros

  • Interactive dashboards made easy
  • Extensive documentation and a very active community

Cons

  • Paywall for enterprise features
  • If you work with React.js, you’ll need to manually port your components to Dash

#10 Django Python Web Framework

How can there be a post on the top 10 list of web frameworks for Python that doesn’t include Django? This is kind of a cheat entry, since Django is a foregone conclusion. It’s insanely popular to the point where many first-time web developers get their feet wet by interfacing with Django.

Whether you’re looking to build a business or just kick off an idea, Django is the best solution. It’s fast enough, secure enough, scalable enough and production tested enough to handle just about any webdev task. And it’s built with microservices in mind. It takes care of user authentication, database handling – all the standard routines – via a huge repository of libraries. The community support is unparalleled and continues to grow with the resurgence of Python.

If this blogpost confused you with too many options, just go with Django!

Pros

  • The battle hardened, tried and true, all purpose webdev framework
  • “Batteries included” – everything you need is provided out of the box

Cons

  • Opinionated – you either like the “Django way” of doing things or you don’t
  • Requires regex for URL routing — regex! 🙁

Next Steps

To get started, you can:

  1. Create a free ActiveState Platform account
  2. Download:
    1. ActivePython, which is a pre-built version of Python containing hundreds of packages that can help you solve your common tasks
    2. The “Top 10 Python Web Frameworks” build, which contains a version of Python and most of the tools listed in this post so you can test them out for yourself.

NOTE: the simplest way to install the Top 10 Web Frameworks environment is to first install the ActiveState Platform’s command line interface (CLI), the State Tool.

  • If you’re on Windows, you can use Powershell to install the State Tool:
    IEX(New-Object Net.WebClient).downloadString('https://platform.www.activestate.com/dl/cli/install.ps1')

  • If you’re on Linux / Mac, you can use curl to install the State Tool:
    sh <(curl -q https://platform.www.activestate.com/dl/cli/install.sh)

Once the State Tool is installed, just run the following command to download the build and automatically install it into a virtual environment:
state activate Pizza-Team/Top-10-Python-Web-Frameworks

Cover image credit : Background supplied by jooinn.com

Related Blogs:

Top 10 Python Tools To Make a Developer’s Life Easier

Creating Python Dashboards: Dash vs Bokeh