LanguagesPythonTop Python Frameworks

Top Python Frameworks

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Since Guido Van Rossum created Python way back in 1991, it has grown into one of the most popular web development languages today. Python is a dynamically typed, interpreted, and object-oriented language that helps programmers to write code in a concise and logical way. In addition to the core language, there are various libraries and frameworks available for every possible technical domain.

Although Python comes with everything you might need, using a framework can help developers reduce development time as it provides boilerplate code for common details like protocols, sockets, and much more, thus freeing programmers to focus on application logic. Another advantages of frameworks is that they are typically open-source, secure, well documented, and efficient. Each framework has its own pros and cons, so the choice of a Python framework very much depends on the project requirements as well as the developer’s individual preferences.

In this programming tutorial, we will learn about the main types of Python frameworks, before delving into which frameworks are regarded as the cream of the crop.

Types of Python Frameworks

Whereas JavaScript frameworks can be divided into server and client-side, Python frameworks can be broken down into three distinct types, as follows:

  1. Full-stack Framework: Such frameworks are a one-stop solution for all developer requirements. From form generators and validators, to template layouts, full-stack frameworks come with everything developers might need.
  2. Microframework: Slightly more light-weight than their Full-stack counterparts, Microframeworks do not offer additional functionalities and features, such as database abstraction layer, form validation, and specific tools and libraries. Hence, developers need to add a lot of code and additional requirements manually.
  3. Asynchronous Framework: A newcomer to the Python framework arena, asynchronous frameworks are a type of microframework that allows for handling a large set of concurrent connections. Typically, asynchronous functionality is provided via Python’s asyncio library.

Now it is time to turn our attention to specific Python frameworks worth your consideration.

Django Python Framework

django unchained

No, not that Django!

Django Web Framework

Django is a free and open source high-level Python web framework that encourages rapid development and clean, pragmatic design. Built by a team of experienced developers, it takes care of much of the hassle of web development, so you can focus on writing your app without needing to reinvent the wheel.

Features of Django

  • Fast – Django was designed to assist developers in taking their applications from concept to completion as quickly as possible.
  • Secure – Django helps developers avoid many common security mistakes.
  • Scalable – Django is able to quickly, and flexibly, scale.

The data-model syntax offers many rich ways of representing your models. Here is a quick example of Django in action:

from django.db import models

class Reporter(models.Model):
    full_name = models.CharField(max_length=70)
    
    def __str__(self):
        return self.full_name

class Article(models.Model):
    pub_date = models.DateField()
    headline = models.CharField(max_length=200)
    content = models.TextField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
    
    def __str__(self):
        return self.headline

Pros of Django for Python

  • Speed and scalability – Django skips a lot of the manual steps that would normally be involved in building something that can slow web developers down, allowing them to focus on creating great apps.
  • Community support – Having been around for over sixteen years (half the life of the Python language itself), and with such a broad range of applications, the Django community is thriving.
  • Documentation – Django boasts one of the best sets of documentation among open-source frameworks. It is precise, exact, and well-organized for web developers just starting out in Python.
  • Security – Django has a user authentication system, and includes Clickjacking, XSS, CSRF, and SQL injection protection, as well as HTTPS. Even better, all of Django’s security features come already set up, so programmers do not have to spend any time configuring it.

Cons of Django for Python

  • Not good for simpler projects – Django is a high-level framework, so it lends itself more to more complicated projects. If you are looking for the right framework for smaller, easier projects, then you might want to look elsewhere.
  • Can lead to slow websites – Although you can build web apps quickly with the Django framework, sometimes it can result in your website running quite slowly. Not related to the Python language or Django per se, the issue stems from the amount of resources you’re accessing with the framework.
  • Lack of conventions – A coding convention is a group of guiding principles to follow when using a web framework. Unlike a framework like Rails, which espouses “Convention over Configuration“, Django does not use any conventions, which can cause some programmers to progress more slowly.

Read: Top Online Courses to Learn Python

Flask

Flask web framework

Flask is considered to be a microframework and is inspired by the Sinatra Ruby framework. It depends on the Werkzeug WSGI toolkit and the Jinja2 template.

The main idea behind Flask is to allow web developers to build a solid web application foundation. From there, you can use any extensions you might need.

Flask was originally created by Armin Ronacher as an April Fool‘s joke that wound up becoming so popular it became a respected and well-accepted tool for building web applications. The name is a play on the Bottle framework. Flask is one of the most popular web development frameworks among Python developers today (just barely behind Django).

Features of Flask Web Framework

  • Development server and debugger
  • Integrated support for unit testing
  • RESTful request dispatching
  • Supports Jinja templating
  • Support for secure cookies
  • WSGI 1.0 compliant
  • Unicode-based
  • Extensive documentation
  • Compatible with Google App Engine
  • Robust extensions available

Developers can use Flask to create a database using a Python file that will generate an SQLite .db database file. Here is some example Python code that inserts data into a database using the Flask framework:

import sqlite3

connection = sqlite3.connect('database.db')


with open('schema.sql') as f:
    connection.executescript(f.read())

cur = connection.cursor()

cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
            ('First Post', 'Content for the first post')
            )

cur.execute("INSERT INTO posts (title, content) VALUES (?, ?)",
            ('Second Post', 'Content for the second post')
            )

connection.commit()
connection.close()

Pros of Flask

  • Easy to understand – The Flask framework is easy for beginners to get the hang of. The simplicity in the flask framework enables the developer to navigate around their applications and learn from them.
  • Very flexible – Almost all the parts of flask are open to change, unlike some other web frameworks.
  • Testing – Flask supports unit testing through its integrated support, built-in development server, fast debugger, and restful request dispatching.

Cons of Flask

  • Developer beware! – As easy as it is for an amateur or a beginner to learn web development with the Flask framework, a bad developer can just as effortlessly write low-quality code.
  • Scale – Flask has a singular source, which means that it handles every request in turn. So, if you are trying to serve multiple requests, it will take more time. With fewer tools at your disposal, you may need to install more modules, although this could be mitigated by using Python specialized hosting.
  • Modules – Using more modules requires additional third party involvement, which could result in a security breach. Moreover, the process and development is no longer between the web framework and the developer, because of the involvement of other modules. That could increase the security risk if a malicious module is included.

AIOHTTP
Aiohttp Python Framework

 

Making heavy use of Python’s async and awaits 3.5+ features as well as the asyncio library, AIOHTTP falls squarely in the asynchronous framework camp. AIOHTTP works equally well as a client or server web framework as it provides a request object and router to enable the redirection of queries to functions.

Features of AIOHTTP:

  • Can act as either a Client or HTTP Servers.
  • Supports both Server WebSockets and Client WebSockets out-of-the-box without the need for callbacks.
  • Web-server has Middleware, Signals, and plugable routing.

Here is a short client example using AIOHTTP and Python:

import aiohttp
import asyncio

async def main():

    async with aiohttp.ClientSession() as session:
        async with session.get('http://python.org') as response:

            print("Status:", response.status)
            print("Content-type:", response.headers['content-type'])

            html = await response.text()
            print("Body:", html[:15], "...")

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

This prints:

Status: 200
Content-type: text/html; charset=utf-8
Body: <!doctype html> ...

Bottle

Bottle Web Framework

 

Bottle is a fast and simple microframework for smallish web applications as well as APIs. It uses a single standard library of code – the Python standard library. This library includes a built-in template engine, exception handling, and a few other basic features. Projects are compiled into a single source file. Bottle is the perfect choice for the beginner who wants to learn more about how python frameworks work and how to build personal-use apps.

Features of Bottle Python Framework:

  • Provides access to form data, cookies, file upload, and other HTTP-related metadata.
  • Includes the Request-dispatching route.
  • Offers a built-in HTTP server
  • Has plugin support for various databases.
  • Third-party template engines and WSGI/HTTP servers can also be utilized.

Here is an example of “Hello World” in a bottle!

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)

Web2Py

Web2Py web framework

 

Web2Py is a framework that falls into the fullstack category. It is an open-source and scalable framework that supports all operating systems. Web2Py comes with its own web-based integrated development environment (IDE) that has all the features that an IDE should have, such as a debugger, code editor, and one-click deployment. The only downside is that the IDE can not work with Python 3.

Features of Web2Py:

  • Ability to run on any web hosting platform that provides support for either Python or Java
  • Backward compatibility
  • Built-in data security for preventing several common vulnerabilities, including cross-site scripting, injection flaws, and malicious file execution
  • Virtually no installation and configuration requirements
  • Follows Model-View-Controller (MVC) pattern
  • Provides support for internationalization
  • Readability of multiple protocols
  • Role-based access control

As you can see in the code example below, it does not take much code to display a greeting message:

def index():
    return "Hello from MyApp"

CherryPy

CherrPy web framework

In no way associated with the Warrant song, CherryPy is one of the oldest microframeworks on the scene. CherryPy is an open-source and object-oriented framework that takes a decidedly minimalistic approach. It lets developers use any technology for accessing data or template creation, but applications created by the framework are stand-alone Python applications that include an embedded multi-threaded server.

Features of CherryPy:

  • A number of out-of-the-box tools for authentication, caching, encoding, sessions, static content, and much more
  • A flexible built-in plugin system
  • HTTP/1.1-compliant WSGI thread-pooled web server
  • Inbuilt support for coverage, profiling, and testing
  • Offers simplicity for running multiple HTTP servers simultaneously
  • Powerful configuration system
  • Runs on Android

Here is an example of a typical CherryPy application:

import cherrypy

class HelloWorld(object):
    @cherrypy.expose
    def index(self):
        return "Hello World!"

cherrypy.quickstart(HelloWorld())

CubicWeb

CubicWeb web framework

 

CubicWeb is a full-stack framework that is free to use. CubicWeb is also referred to as a semantic web application framework. One distinguishing feature of CubicWeb is its use of cubes instead of the standard models and views framework. In fact, it’s CubicWeb’s use of reusable cube components that makes applications both easy to read and debug.

Features of CubicWeb:

  • Support for multiple databases
  • Provides security and reusable components
  • Uses RQL (relational query language) for simplifying data related queries
  • Provides support for Web Ontology Language (OWL) and Resource Description Framework (RDF)

Modeling your data is usually one of the very first steps of app development. Once your model is implemented, your CubicWeb application is ready to run. From there, you can incrementally add functionalities for your users. Here are a couple of Entity classes:

class City(EntitySchema):
  name = String(required=True)

class Museum(EntityType):
  name = String(required=True)
  is_in = SubjectRelation("City", cardinality="1*")

Dash

Dash Python Framework

 

Dash is an open-source microframework used for developing analytical web applications. This framework quite popular among data scientists who are not terribly well versed in web development. For front-end rendering it uses ReactJS. Applications built using dash can also be used to run web servers like flask and then communicate with JSON packets via standard HTTP requests. Since dash applications can be rendered in the browser and deployed in the server it is considered to be cross-platform and mobile-ready.

Features of Dash Python Framework:

  • Requires little coding to develop applications
  • A high level of customization is offered
  • Error handling is simple
  • LDAP integration (Dash Deployment Server)
  • Plugin support is also there

Dash apps make liberal use of callback functions; these are automatically called by Dash whenever an input component’s property changes, in order to update some property in another component (the output). Here is an example of an HTML layout backed by a callback function using Dash and Python:

from dash import Dash, dcc, html, Input, Output

app = Dash(__name__)

app.layout = html.Div([
    html.H6("Change the value in the text box to see callbacks in action!"),
    html.Div([
        "Input: ",
        dcc.Input(id='my-input', value='initial value', type='text')
    ]),
    html.Br(),
    html.Div(id='my-output'),

])

@app.callback(
    Output(component_id='my-output', component_property='children'),
    Input(component_id='my-input', component_property='value')
)
def update_output_div(input_value):
    return f'Output: {input_value}'

if __name__ == '__main__':
    app.run_server(debug=True)

Falcon

Falcon Web Framework

 

A microframework aimed at rapidly building web APIs, Falcon is another wildly popular Python framework. Unlike other Python frameworks that require loading a lot of dependencies for building HTTP APIs, Falcon allows developers to build a cleaner design that enables HTTP and REST architectures.

As per the benchmark test conducted by Sanic, Falcon is able to handle most requests with the same hardware than all its contemporaries. The Python framework aims to have 100% code coverage. Falcon is used by big players like LinkedIn, OpenStack, and RackSpace.

Features of Falcon Python Framework:

  • An extensible and highly-optimized code base
  • DRY request processing through middleware components and hooks
  • Ease of access for headers and bodies via request and response classes
  • Extra speed boost with Cython support
  • REST-inspired resource classes and URI templates offer intuitive routing
  • Unit testing via WSGI helpers and mocks
  • Upfront exception handling

Falcon encourages the REST architectural style, and tries to do as little as possible while remaining highly effective. Here’s a resource that returns a quote:

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


app = falcon.App()
app.add_route('/quote', QuoteResource())

Giotto

Giotto web framework

Giotto is a full-stack MVC-based framework that separates model, view, and controller so that developers and system admins can work independently. It encourages a functional style where model, view and controller code is strongly decoupled. Giotto enables users to build apps on top of the web, IRC (Internet Relay Chat), and command-line by including a controller module.

Features of Giotto Web Framework:

  • Very terse code. A full featured blog application is under 300 lines of code (including templates)
  • Generic views, generic models and multiple pluggable controllers.
  • Free RESTful interface along with your normal “browser POST” CRUD site.
  • Functional CRUD patterns that do away with the need for Django-style form objects.
  • Provides feature of automatic URL routing.
  • Built in cache (supports Redis and Memcache, and an API for supporting any other engines)
  • Database persistence with SQLAlchemy.
  • Jinja2 for HTML templates (with an API for extending for other template engines)

Here are sample manifest.py and multiply.html files for a multiplication calculator:

from giotto.programs import ProgramManifest, GiottoProgram
from giotto.views import jinja_template, BasicView

def multiply(x, y):
    x = int(x or 0)
    y = int(y or y)
    return {'x': x, 'y': y, 'result': x * y}

manifest = ProgramManifest({
    'multiply': GiottoProgram(
        model=[multiply],
        view=BasicView(
            html=jinja_template('multiply.html'),
        ),
    ),
})


<!DOCTYPE html>
<html>
    <body>
        {{ data.x }} * {{ data.y }} == <strong>{{ data.result }}</strong>
    </body>
</html>

Sanic

Sanic web framework
Sanic Python framework

 

Sanic is an asynchronous, simple and open-source Python framework built on top of the uvloop. It was developed specifically for offering fast HTTP responses via asynchronous request handling. Sanic’s asynchronous request handlers are compatible with Python 3.5’s async/await functions, which result in enhanced speed as well as offering non-blocking capabilities. During a benchmark test with one process and 100 connections, Sanic was able to handle as much as 33,342 requests in a single second!

After installing, Sanic has all the tools you need for a scalable, production-grade server – out of the box, including full Transport Layer Security (TLS) support.

Features of Sanic Python Framework:

  • Simple and lightweight
  • Unopinionated and flexible
  • Performant and scalable
  • Community driven
  • Able to read and write cookies
  • Allows different types of logging, such as access log and error log
  • Class-based views
  • Handlers with easy to apply decorators support
  • Plugin support
  • Supports blueprints for sub-routing within an application
  • The configuration object can be modified either by using dot-notation or like a dictionary

Here is a “Hello World” app written in Sanic and Python. As you can see, the code is quite terse!

from sanic import Sanic
from sanic.response import text

app = Sanic("MyHelloWorldApp")

@app.get("/")
async def hello_world(request):
    return text("Hello, world.")

Growler

Growler web framework

 

Written atop Python’s asyncio library, Growler is an asynchronous micro web framework inspired by the NodeJS and the Express/Connect frameworks.

Unlike other conventional Python frameworks, requests in Growler aren’t handled in the framework but by passing through middleware technology.

A top choice among Python frameworks for easily and quickly implementing complex applications, Growler was originally developed by its author to simply learn how to use asyncio library at its lowest levels.

Features of Grower Web Framework:

  • Easy to see program flow due to lack of required callbacks and proper try/except blocks
  • Support for a variety of open-source packages
  • Uses decorators which results in cleaner and more reusable code
  • Ziapp module allows zipping an entire application into a single executable file

Here is the Growl notifications widget from the js api. demo page:

var growler = new Growler({}, "growlerDijit");
growler.startup();

growler.growl({
 title: "Warning!",
 message: "Best check yo self, you're not looking too good.",
 level: "warning"
});

A word of warning: the last commit to GitHub was on Mar 8, 2020, and the growler.rocks domain is now up for grabs, which all points to the project being in an inactive state.

Final Thoughts on the Top Python Frameworks

In this tutorial, we covered the top Python frameworks, exploring such notables as Django, Flask, AIOHTTP, Bottle, and Web2Py. Choosing the right framework largely depends on the needs or you web development or app programming needs – in general, however, you cannot go wrong with any option on our list.

Read: Top Collaboration Tools and Software for Web Developers

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories