Django vs Flask: Which Framework Is Better?
If you’re about to develop a web app in Python, your first consideration may be whether to use Django or Flask. This guide will help you decide which of these two frameworks to use.
I’ve based this guide on my experience with the two frameworks over recent years. I’ll start by asking whether you need a framework at all, and then help you assess various aspects of both Django and Flask. While this guide helps you make a choice between Django and Flask, these parameters should enable you to assess any framework.
I’ll assume you have a basic knowledge of Python and know how to create web apps.
Do You Need a Framework?
If you’re starting development of a web app, you should first outline your requirements before narrowing down on a framework. If you’re building a product website, or a portfolio, with contact forms for enquiry, you may choose a static site generator with external forms like JAMstack. For a fairly simple web app, you may not wish to go with a Python-based solution at all. A web framework is the right choice when you’re building a more complex web app. Utilizing a web framework’s underlying processes allows you to focus on your app’s development without worrying about the underlying processes that power it.
Although Python is a scripting language, web frameworks like Django and Flask have made it accessible to web developers. The use of a web framework takes care of monotonous tasks like a routing mechanism. The framework is responsible for a pipeline to connect a specific URL to the logic behind the execution. This allows you to focus on the core of your web app instead of worrying about the standard processes common to all web apps.
In the 2018 Python Developer Survey by JetBrains, Flask (47%) and Django (45%) were the two most commonly used frameworks by a significant margin. Flask is a minimalist web framework in Python which allows you a lot of flexibility to design your app. Django is a framework that provides a lot of structure to the web app, with a handful of useful features.
Assuming you’ve analyzed your requirements and believe that a framework works best for you, I’ll now move on to compare the two frameworks.
Django vs Flask: General Trends
Django has been around since 2005, and has matured into a popular web framework. It’s a high-level, open-source framework that encourages quick development through out-of-the-box features such as a powerful ORM and a GUI-based Admin. Flask was first released in 2010, and has now developed into a microframework. Flask’s out-of-the-box capabilities are the essentials for web development: URL routing, request handling, and templating.
Here are some metrics about the two frameworks:
Notice that the number of commits in Flask are only about 15% that of Django, which indicates that Flask contains only the essentials of a framework, giving you the opportunity to explore further. You can also see that Flask has just edged Django in terms of popularity.
Google Trends indicates a shift in the mindset of developers too. Flask is catching up with Django in terms of popularity. I’ve prefixed “Python” to both search terms, because “Django” spiked as a search term following the release of the movie Django Unchained in late 2012. "Flask" on its own also has various meanings.
The trends of questions asked in Stack Overflow is still skewed towards Django, though. This indicates that even though Flask is gaining popularity, the community support for Django is staying strong.
There are prominent web apps built with these frameworks. Instagram is the largest app built entirely with Django. Other popular websites built with Django are Disqus and BitBucket. The cloud communications service provider Twilio uses Flask for its API. Though the development of Pinterest started with a heavily modified version of Django and Tornado, it has since moved to Flask.
Getting Started with Django and Flask
So, how easy is it to start development with Django and Flask? When you start working on Django or Flask, the general approach is to work with the tutorial that you find on the documentation of the site.
In Flask’s Quickstart Guide, a simple version of the “Hello World” app in Flask is described. Download its latest version through pip and create an application file. If you run the server, you should be able to view the home page. The rest of the guide is to help you incrementally add features to Flask. The simplicity of the getting started tutorial lies in the minimal philosophy of Flask.
The getting started section page on the Django documentation contains a seven-part tutorial. Though you have a running development server after the first part, this entire experience is designed to familiarize you with the core components of Django like the ORM, Django Admin, forms and templates. Completing the tutorial introduces you to the Django workflow: URL > View > Model > Template. When a reader visits a URL, Django matches it with the available URL patterns and redirects it to a certain view. A view is a function that analyses the inputs received (in the hello world example, you would have no input), makes necessary queries to the database (Model) and returns a response. This response is parsed by a template and displayed as required.
While getting started with Flask seems relatively easier, the benefits of putting in the extra effort into Django are observed when creating a more complex app. This is a direct consequence of the difference in philosophies of the two frameworks: the simplicity and flexibility of Flask, compared with the “batteries included” approach of Django. I’ll discuss the consequences of this shortly.
Django vs Flask: Anatomy of a Project
In this section, I’ll examine various components in each framework. First, I’ll look at the how they handle URLs, databases and responses, other useful features, and security considerations.
URL Routes and Views
Django and Flask both have URL routing and views by default, through their implementation is slightly different. Django separates the URL and logic handling. You define your URL patterns (urls.py
), which direct to the handlers (views.py
).
In Flask, the URL patterns are commonly declared as decorators or explicitly through the application object. While this doesn’t inherently pose a disadvantage in terms of development, as your project grows larger, it may pose a challenge unless you impose a structure. If you add URLs as decorators, you’ll need to make a lot of changes if you decide to change the URL patterns of your app at a later stage of development. It may be a good idea to create a centralized URL map.
Database Support
Django has an underlying database layer and a robust ORM system. Django, by default, has support for popular databases with MySQL, Oracle, SQLite and PostgreSQL. If you’re starting a project, you can defined your database structure in your models and Django automatically creates the tables for you. If you’d like to link to an existing table, it can also be done through custom field names in the models.
Flask, by default, doesn’t support databases. You need to use a third-party app like SQLAlchemy, which can emulate the features of the Django ORM system. You should note that it’s possible to use SQLAlchemy in Django if you really want to, but the Django ORM already handles the security pieces.
If you use a NoSQL database, the flexibility that Flask provides makes it easier to integrate with a plugin like Flask-PyMongo. Integrating a NoSQL database with Django raises a list of compatibility issues, as it limits the functionality of the Django ORM.
Over the ORM capabilities, Django also provides you a capable admin interface, which, once enabled, can help you manage database objects effectively through a web interface.
Templates
Flask uses the Jinja2 tool as its templating engine. It seamlessly binds together static and dynamic content to reduce redundancy. Django’s own templating engine has similar syntax to Jinja2 and you may not notice much difference.
Jinja2’s documentation lists the major differences between the two templating engines. I don’t feel that one has any advantage over the other in terms of development speed.
Other Features
Django and Flask both have integrated testing platforms. You can use Python’s unittest in both projects to create test clients and emulate requests.
Django has a few other advantages over Flask. For instance, Django has an inbuilt caching framework. Django provides you a user management system, which handles authentication and authorizations. All of these can be implemented in Flask too, through the use of third-party plugins. Flask has over seven hundred plugins available on the Python Package Index.
While Django has a number of useful features as a part of the core framework, it has a plethora of plugins too. While there’s no official site that lists Django plugins, djangopackages.org does a good job of documenting available Django packages. As of late 2019, it lists over four thousand Django packages.
Security
Django has a lot of in-built security measures. Some of them are listed below:
- The use of Django templates gives you protection against cross site scripting (XSS) attacks by escaping special characters that are used in these attacks. Jinja2 also provides this protection by default.
- You can enable the use of CSRF protection when using Django forms. CSRF protection in Flask can be done manually by inserting a random string and validating it on form submission.
- By default, Django interacts with the database using the ORM, which protects you against SQL injection. Django allows custom SQL too, so you should be careful when using such queries. If you use SQL Alchemy, user inputs are sanitized by default.
- Django also provides you clickjacking protection by preventing your site from loading inside a frame.
While these security features are mostly enabled by default in Django, you should read about them to understand their limitations. Here’s a list of security considerations in Flask.
Django vs Flask: Summary
In this guide, we first examined whether you really need a web framework for your project.
We then looked at the history and recent trends of Django and Flask, two popular Python frameworks. While Django is a more mature project, Flask has gained a lot of popularity recently.
We then examined the ease of starting a project in either framework. While a Hello World app is fairly easy to create in Flask, the initial learning curve of Django ensures quick development in the future.
Next, we looked at how each framework handles URLs, databases and HTTP responses. Django has inbuilt support for many relational databases, but Flask’s flexibility allows you to work more easily with NoSQL databases.
We looked at a few extra features that Django provides from the outset.
We finally assessed certain security considerations for web apps and how to enable them in Django and Flask. While Django provides many security features by default, it’s a good idea to read about their limitations to truly protect your app.
Final Thoughts
We finally come to the important question! What is the best framework? Unfortunately, there’s no universal answer to this question!
Are you going to have a lot of dynamic content in your web app? Is your project heavily going to use relational databases? Do you prefer to build your app with a bunch of read-to-use features? If your answer is yes to most of these questions, you should go ahead with Django.
Have you been coding in Python for a long time? Would you like to develop your application based on your own structure? Are you going to use NoSQL in your project? Do you want a framework that is highly customizable and adaptable to your needs? If you fall in this category, you should opt for Flask.