Flask vs Django

A comparison of the two dominant Python-based web frameworks.

Flask and Django are the two most popular Python-based web frameworks. Both are mature, open-source, and have many happy users. A natural question therefore is: which one to use?

In this article I will cover the relative pros and cons of each framework, provide real code examples, and links to further resources for learning each.

Micro vs "Batteries-Included" Framework

The biggest difference between Django and Flask is their overall approach. Bluntly stated, Flask is simpler but does less while Django has far greater functionality but at the cost of more complexity.

Flask is a simple, lightweight, microframework meaning it provides only basic functionality such as URL routing, templates, cookies, a debugger, and a development server. This makes it arguably simpler to start with and at only ~29,000 lines of code, it's possible--and recommended--to read through the source code to figure out what's happening behind the scenes.

When developing a Flask application, the developer is in complete control. It's up to the developer to add additional functionality such as connecting to a database, handle forms, security, authentication, and so on. This makes Flask a great learning tool if you're brand new to web development in general, however that also means it's easier to make mistakes. As a result, Flask is often quite popular at the two extremes of Python web developers: those who are brand new or who are experts and have very particular requirements that require complete flexibility.

Django, by contrast, is a full featured "batteries-included" framework. It has roughly 10x as many lines of code as Flask, ~290,000, but also comes with almost every feature a website will need built-in including database connections, fantastic security, forms, a powerful user admin, and a robust ecosystem of 3rd party packages. If you know what you're doing, Django is much faster to use since you can be up and running with far less code the developer has to write themself than with Flask.

The downside of Django's power is that it has a steeper learning curve. The larger codebase takes much longer to master. If you're brand new to web development, many elements in Django will appear like "magic" at first.

Jobs

If you're looking for a job as a Python web developer, Django is the better choice. There are almost twice as many listings for Django developers as for Flask on major job boards such as Indeed.com.

However, this disparity is likely due to the fact that Django is a much more specific choice than Flask. A startup or company can run almost all of their services just on Django whereas Flask is often used alongside other technologies given its lightweight footprint.

The most employable approach is to truly master Python first and then add web development knowledge with either Django or Flask on top.

Community

Django has the larger, more organized community of the two. There are over 1,800 committers to the Django codebase vs around 550 for Flask. On StackOverflow there are ~212,500 Django questions compared to ~31,500 Flask questions.

Django also has annual conferences in both the United States, Europe, Australia, and Africa. Flask does not have a similar level of conferences although there are active discussions for both frameworks at PyCon events.

Speed

When it comes to speed of a web application, Django and Flask are basically the same. You can see a more detailed rundown here. Ultimately what makes a website "slow" is almost never the underlying programming language or web framework. Instead, it is slow database queries (too complex, not enough indexes), lack of caching, or not using a CDN for front-end assets.

Hello, World comparison

Flask famously features a "Hello, World" example right on its homepage. Here's how to configure it. Navigate to a new directory on your computer, such as a flask directory on your Desktop if you're using a Mac. Then install Flask.

$ pip3 install flask

Create a new file, hello_flask.py, and populate it as follows:

# hello_flask.py
from flask import Flask, escape, request

app = Flask(__name__)

@app.route('/')
def hello():
    name = request.args.get("name", "World")
    return f'Hello, {escape(name)}!'

Then start the Flask server from the command line:

$ env FLASK_APP=hello_flask.py flask run
* Serving Flask app "hello_flask.py"
* Environment: production
WARNING: This is a development server. Do not use it in a production deployment.
Use a production WSGI server instead.
* Debug mode: off
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Navigate to http://127.0.0.1:5000/ and there is a nice "Hello, World!" message.

What about Django? There is no equivalent example on the Django website however we can, in fact, accomplish a similar feat with only a few more lines of code. Navigate to another directory, perhaps called django on your Desktop. Then install Django:

$ pip3 install django

Create a hello_django.py file with the following code:

# hello_django.py
from django.conf import settings
from django.core.handlers.wsgi import WSGIHandler
from django.core.management import execute_from_command_line
from django.http import HttpResponse
from django.urls import path

settings.configure(
    ROOT_URLCONF=__name__,
    DEBUG=True,
)

def hello_world(request):
    return HttpResponse("Hello, Django!")

urlpatterns = [
    path('', hello_world)
]

application = WSGIHandler()

if __name__ == "__main__":
    execute_from_command_line()

And start Django's built-in web server with the following command:

$ python3 hello_django.py runserver
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 17, 2019 - 13:48:54
Django version 3.0, using settings None
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Navigate to Django's standard port of 8000, http://127.0.0.1:8000/, to see the Django Welcome page.

So Django is a bit longer, largely due to the fact we explicitly import functionality more granularly than in Flask. However it's still possible to do a single "Hello, World" from one file and if we explored further, Django has given us much more functionality that is readily available. With Flask, to move beyond the absolute basics installing and configuring additional packages is required.

But the important point is that while "Hello, World" might be a meaningful comparison for a programming language, it is largely meaningless when comparing web frameworks. A real-world Flask application is not contained in a single file, nor is a Django application. So using either benchmark is quite limited in its usefulness.

Looking Forward

Python has added native async support starting in Python 3.5 and Django 3.0+ has this built-in as a major feature. Flask is literally built around a synchronous model and though there are multiple efforts to add async at the moment, none is ready for prime time.

Killer Features

Flask: - If you need a non-relational database - Want a lightweight codebase

Django: - Robust documentation - Vibrant community - Powerful built-in admin - Async capabilities - Security is a priority

Conclusion

So which web framework to choose?

Ultimately a Flask developer strongly prefers the granular level of control it provides, while a Django developer enjoys relying on a large community that with 15+ years of experience has made and frees the developer to focus on what makes a website different, not recreating the wheel.

A Django proponent would say that a Flask developer eventually rebuilds Django itself, poorly and slowly. A Flask advocate would counter that Django is far too heavy, slower for prototypes, and harder to customize as needed at scale.

My personal advice is that most of the time Django is the better choice. Combined with Django REST Framework it can quickly build powerful APIs, while Flask requires more work and more chances to make a mistake. The best approach is to build a few basic CRUD apps with both and decide for yourself which fits your style better.