Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Python is an excellent choice for web development — thanks to frameworks like Flask and Django, building robust, high-performance web apps becomes much easier.The focus of this article is the following question: what are the differences between Flask and Django? The differences we’ll outline below will help you understand which framework to choose when building a web app.
Python is a fan favorite on our blog: with its awesome qualities like readability, power, and versatility, it often feels like we could be producing Python-focused content every day — and we still wouldn’t cover all of its potential.
In previous articles, we explored topics like web scraping and deep learning — Python is typically associated with these areas. However, we should also keep in mind that Python is an excellent choice for web development — thanks to frameworks like Flask and Django, building robust, high-performance web apps becomes much easier.
The focus of this article, therefore, is this question: what are the differences between Flask and Django? The differences we’ll outline below will help you understand which framework to choose when building a web app.
Before we start comparing this duo, we need to actually understand the bigger picture: why do web developers need frameworks at all? With front-end JavaScript frameworks like React, Angular, and Vue being the hottest technologies on the market right now, it’s critical to understand why developers pour so much time and resources into creating such technologies.
The power of frameworks lies in several factors — let’s outline them in detail. Before we do that, however, let’s reiterate one important thing: frameworks aren’t designed to “simplify” everything. Building a basic web page with vanilla JavaScript is much easier than utilizing React; each framework has a certain learning curve — but the benefits they offer are totally worth the effort.
When it comes to web frameworks in particular, both Flask and Django offer additional benefits related to HTTP operations, web security protocols, and so on. This means that building a (somewhat) large web app absolutely requires a framework. Here’s the million-dollar question: which one to use?
Even though it’s tempting to compare these technologies directly (e.g. “Framework A is better than Framework B!”), — there is no “better” framework out of the two, only a framework that fits your own needs. Both Flask and Django are an excellent choice when it comes to web development. The tricky part is understanding the differences between them, so let’s try and see how they compare in areas like security, speed, performance, popularity, and some others.
First of all, we should take a look at the focus and philosophy of Django and Flask — that is, which goals their respective developer teams had in mind when creating these frameworks.
Django is probably best known for its “batteries included” approach, meaning that it comes prepackaged with a large number of useful tools (imagine a swiss army knife but its individual parts actually do the job quite well) that the developer can choose from. These include components like web server, template system, caching framework, and many others.
Django boasts the following design philosophies:
Flask, on the other hand, chooses a different approach: it’s designed to be as light-weight as possible, only offering basic functionality. Should the developer wish to extend the functionality of a Flask app, they’d have to rely on third-party tools and extensions (as we’ll find out later, this approach can pose certain security issues).
Due to its small size (and a small set of features when compared to Django), Flask is often referred to as a “microframework”, i.e. a framework which, as the name suggests, offers only rather limited functionality. For instance, you don’t get features like an ORM, access control, or authentication out of the box when working with this framework. Flask, among other things, is a great example of Pythonic (i.e. following the best Python practices) code — you can check its source code here.
Although popularity shouldn’t be a deciding factor, we’re still curious to see how Flask and Django compare in this regard. JetBrains, the team behind a popular Python IDE called PyCharm, provides this data in their annual Python Developers Survey. Let’s visualize it:
As we can see from this chart, Django and Flask dominate the Python web frameworks market. While Flask fans can use this data to claim superiority over Django, here’s a more important takeaway: both of these frameworks are (almost) equal in popularity, so it’s unlikely that they share the same functionality. This reinforces the point we made earlier: these frameworks have a lot of differences that you have to take into account.
Greeting the world with a simple “Hello, World!” program is a common way to be introduced to technology. Let’s continue this tradition and see how this little app program can be implemented in these frameworks. (Disclaimer: It wouldn’t be fair to judge a technology by the way it implements a “Hello World!” program, so this section is designed to simply whet your appetite.)
In Flask, this task is trivial: upon Flask’s installation (pip3 install flask —user
or pip install flask —user
), we create a Python script flaskhello.py
and paste the following code:
from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return "Hello, World!" if __name__ == "__main__": app.run()
When we run this script in terminal (by inputting python3 flaskhello.py
or python flaskhello.py
), we get the following output:
>>> Running on http://127.0.0.1:4000/ (Press CTRL+C to quit)
The information above tells us our port number (4000
in my case), while 127.0.0.1
signals that the web app is running locally. Upon visiting http://127.0.0.1:4000/
, we are greeted with the “Hello, World!” message. All according to plan!
In Django’s case, however, achieving the same result is significantly trickier. We begin with installing Django either via pip3 install django --user
or pip install django --user
. Then, we need to:
urls.py
file to manage the app’s URLs…This area is where Django, undoubtedly, has the upper hand: security is one of Django’s priorities due to its focus on complex web apps.
This doesn’t mean that Flask apps are inherently more vulnerable — both of these frameworks can be targeted by hacking techniques like XSS (“Cross-Site Scripting”), SQL injection, directory traversal, and so on. The important difference lies in the methods that Flask and Django utilize to protect themselves — let’s examine them step by step:
This type of attack utilizes a special type of injection, allowing the hacker to send malicious code (in the form of scripts) via the browser-side script to various end-users. XSS is a common threat because it can be realized in any web application that accepts user input. The following code snippet takes user input and posts it as a message:
<form method="post" action="/"> <input type="text" name="message"><br> <input type="submit"> </form>
The hacker, therefore, can use this vulnerability to perform an Ajax call, effectively gaining control over the user’s account via password hijacking.
Flask offers a feature called Content Security Policy which can protect the web app from this kind of attack. CSP is, in essence, a security mechanism designed to segregate “trusted” (which include JavaScript and CSS files, fonts, etc.) and “suspicious” assets. This is how CSP can be implemented:
@app.route('/', methods=['GET', 'POST']) def user_posts_feed(): if request.method == 'POST': post = request.form['post'] posts.append(post) response = make_response(render_template('post_feed.html', posts=posts)) response.headers['Content-Security-Policy'] = "default-src 'self'" return response
In Django’s case, it is advised to use Django templates as they’re able to protect the website from the majority of XSS attacks — still, they cannot protect against all attacks. Even though Django templates escape those characters considered dangerous to HTML, code like
<style class={{ var }}>...</style>
will not be escaped. This means that the attacker can set var
to 'class1 onmouseover=javascript:func()'
, making the execution of unauthorized JavaScript files possible.
This problem is partially mitigated by the fact that different browsers render imperfect HTML differently; however, outputting content other than HTML requires a new set of escape characters, so it becomes quite a vicious cycle.
An SQL injection is another popular form of attack designed to exploit the vulnerabilities of the database. The hacker can inject harmful code into the database, execute it, and cause significant data loss and/or leakage.
In Django’s case, SQL injection isn’t a major risk factor — the framework’s querysets are immune to this attack thanks to their architecture (which involves separating the query’s SQL code from its parameters). Still, Django also provides the ability to create raw queries and call custom SQL — when misused, they can lead the developer shooting themselves in the foot despite Django’s security measures.
In Flask’s case, there are no out-of-the-box protection mechanisms, so we’ll have to rely on third-party tools. Some of them are:
Of course, Django’s supremacy in security doesn’t mean that Flask is ultimately unsafe. Both Django and Flask provide frameworks (no pun intended) for developers and security specialists to safeguard their applications — but the extent of this safety is solely dependent on the person behind the security measures’ implementation, not on the framework itself.
Being open-source frameworks, both Flask and Django have large communities around them, helping these frameworks progress and improve. Let’s take a look at their respective GitHub accounts to see how dedicated and active their open-source communities are (we can use the data found in Open Hub’s report):
From this data, we can draw a number of conclusions:
[this] …could be a sign of a helpful and disciplined development team.In Flask, 25% of all source code lines are comments; in Django, however, this number is only 16%.
Nowadays, learning general web development is inseparable from learning specific web frameworks — these technologies are offering too many awesome features to be ignored. If you’re only starting to learn web development, Flask would be a solid choice — it would introduce you to the logic of how the web works without overwhelming you with extra details. If you already have some Python experience, developing a web app with Flask will
A common misconception that many beginner programmers share is that “Flask is too simple — it would become a bottleneck in and of itself when I decide to try more complex projects.” In all honesty, this skepticism is unfounded — imagine that every newcomer claims the following: “This laptop would be too slow for my needs — I demand a quantum computer from Google!” ¯\_(ツ)_/¯ We shouldn’t underestimate Flask’s scaling capabilities — it’s not that Django is good and Flask is bad; rather, Django is even more feature-rich and scales better, but it doesn’t disregard Flask’s positive qualities.
Django, on the other hand, is generally recommended to developers with prior Flask/web dev experience as it introduces a plethora of features and settings which you have to manage — this is the price we pay for Django’s extensive functionality.
All things considered, it’s easy to see why both Flask and Django dominate the market of Python web frameworks — their awesome functionality is more than enough to build a high-performance web site. Still, there isn’t really much competition between them: Flask’s focus and use cases are vastly different from those of Django. Next time you start a web project in Python, do make sure to use our neat little overview of these frameworks as a reference. Good luck! 🙂