02Oct
artwork depicting stylized Flask and Django logos
Which one will prevail?

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.

Well, Why Do We Need Flask or Django at All?

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.

  • Standardization: Almost every programming problem has a number of various solutions to it — and sometimes developers cannot agree on the best practice. Frameworks address this conundrum by basically telling the developer: “Alright, do X — and only X! — to solve problem Y. If you don’t like this approach, feel free to stop using me.”
  • Scalability: Enforced standardization allows us to scale web apps with ease because developers have a clear system to follow.
  • Integration: Another benefit associated with standardization is the ability to easily connect other services and tools; a great example is how databases can be easily linked to the framework’s business logic.
  • Last but not least, simplification of development is another great reason to learn a web framework. The process of actually putting local (i.e. residing on your machine) Python code on the web involves a lot of manual steps that beginner programmers find overwhelming, while experienced programmers simply find them tedious. Web frameworks abstract much of this “boredom factor” away via automation.

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.

General Focus & Philosophy

artwork depicting the focus of Django and Flask
(a.k.a. typical use cases)

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:

  • Loose coupling: Different framework elements should not be heavily dependent on each other, unless absolutely necessary.
  • Less code: Boilerplate should be minimized and “Zen of Python” (guidelines for writing Pythonic code) should be adhered to.
  • Quick development: Frameworks’ standardization facilitates quick development (Django’s motto, after all, reads: for perfectionists with deadlines).
  • Explicit is better than implicit: This approach discourages the use of “magic code” (i.e. code that works even though nobody understands why); instead, readability should trump magic code and clever tricks that condense whole functions into one-liners.

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.

Popularity

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:

data visualization of JetBrains Python Developers Survey
Do you know all of them?

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.

Hey — Hi — Hello, World!

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:

  • Create a new Django project.
  • Use Django to create a new app.
  • Create a urls.py file to manage the app’s URLs…
  • … and another URL configuration for the project.
  • Run Django development server.
  • Voila — we finally see the “Hello World!” message.

Security

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:

Flask and Django vs. XSS (Cross-Site Scripting)

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.

Flask and Django vs. SQL Injection

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:

  • Linters and static analysis tools. They provide guidance on code best practices and can, therefore, highlight the logical problems in your code; otherwise, these problems can very well make SQL injections possible.
  • Dynamic application security testing. This software is designed to conduct operational testing, i.e. testing code close to the real-world environment against the common techniques that hackers may use to exploit the given code’s vulnerabilities.
  • Application security monitoring and protection tools. Inspired by the DevOps workflow, these programs aim to provide real-time protection for web apps as users interact with then.

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.

Open-Source Community Involvement

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):

data visualization of open-source communities of Django and Flask

From this data, we can draw a number of conclusions:

  1. As open-source frameworks, both Flask and Django are really active — high numbers of commits and contributors stand testament to this.
  2. In terms of lines of code, Django has roughly 10 times more code than its counterpart. In most cases, judging a project’s functionality by its number of code lines isn’t the right approach — the project’s code may be severely under-optimized. In the case of Django and Flask, however, we can be sure that the developers treat their code seriously (Flask’s code is especially Pythonic). This means that Django’s greater line count translates directly into greater functionality.
  3. Fun fact to counteract the previous point: Open Hub’s report praises Flask developers and contributors for keeping the code well-documented and organized (their page reads: [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%.
  4. Our statement about their almost-equal popularity (as seen in the JetBrains report) is reinforced by the almost-equal Stars count.
  5. By extension, the number of users (i.e. the number of repositories listing the given framework as a dependency) is also similar.
  6. Conversely, Django has the advantage when it comes to the actual development — it boasts higher developer and commit counts. Our experience tells us there may be several reasons for that: in part, Django is 5 years older than Flask (their initial commits happened in 2005 and 2010 respectively); Django also has much greater functionality, so maintaining it would require more effort from the contributors’ part.

Choosing a Framework to Learn

artwork depicting a stylized window interface
Well, there’s no “wrong” answer

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.

Conclusion

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! 🙂

Introduction to Micro Frontends: The New Tech on the Block

Like with all powerful technologies, micro frontends often cause confusion among developers, as evidenced by the ever so popular search queries like “What are micro frontends?” It may be tempting to try and ignore it, but then you’ll be missing out on the amazing opportunities that micro frontends provide — after all, they’re not just a hip trend to follow. In this article, we’ll explore what micro frontends are, what benefits they can bring, how they can be used, and what caveats and pitfalls they pose.

List of Coding Games to Practice & Improve Your Programming Skills

In this post, we’ll take a look at some of the best online games to learn new programming languages and practice your existing programming skills. Some of those are beginner only, others may seem far advanced at the start, but give it a go, and you’ll thank us later. If we forgot to mention something, or you’re building a cool game of your own, do let us know in the comments! Happy learning!

2 Replies to “Flask vs. Django: Let’s Choose the Right Framework for the Job”

  1. Its such good article! For sharing content and such nice information for me. I hope you will share some more content about. Please keep sharing!

  2. great insights and very useful information here! really liked reading it.

Leave a Reply