Flask or Django?

Flask or Django?

Django and Flask are two Python Frameworks which help developers to create Web Applications with high velocity and quality. But what makes them great and powerful and is there so much difference between those? We will compare them and give some code examples. So let’s start!

Django Review

- “The web framework for perfectionists with deadlines”

Django was designed to develop Web Applications with the highest possible productivity and quality. It seems to be such a simple tool that even developer with basic python knowledge is ready to start developing simple web applications. The verity of built-in packages will cover all the needs for the most common situations for services of any size such as user registration, integration with Data Bases, security issues, admin website, etc. For more custom needs such as chat or e-commerce application, Django provides ready to use finished solutions. You can find them on official Django packages resource.

Flask Review

- “Web development, one drop at a time”

Flask was designed as microframework. From the start, Flask has only basic tools such as URL routing, the development server, and template engine.

As a result, it became a really flexible tool for developers with the highest ability to customize any part.

Flask would be a great choice for those who likes to keep everything under control. Also, it's much better to use for Application Programming Interface (API) building, as there is no need to keep an eye on all included packages, which is amazing. Minimalism and simplicity would describe this tool perfectly.

Django VS Flask

It’s not always simple to make a proper choice out of two such great frameworks. Let’s compare those and try to understand in which situation to use Flask or Django.

Django provides it’s own module structure developed in more than 10 years. It’s good when you don’t want to spend time building module structure and get absolutely amazing architecture. Flask provides no code structure at all! This approach gives an opportunity to come up with any structure developers want to use and extend application in any desired way.

Django fully follows Model Template View (MTV) structure. Nowadays, this approach has shown itself as reliable and widely used among other Programming languages and web technologies.

Most of the Flask users still implement MTV solution, but it could be done in a little bit another way, but with the same sense. For example Model View Controller (MVC) or Model Template Resource (MTR).

Django is easy to integrate with any popular database such as PostgreSQL, MySQL, SQLite, and simple make queries using Django Object-Relational Mapping (ORM) system. This tool is built-in and ready to use with minimum setups. It will cover most of the needs to interact with Data Bases.

SqlAlchemy is widely used ORM with Flask. It should be installed separately and set up in application. This could be confusing for not experienced people. But with that, it gives many ways to profile and optimize database interaction. SqlAlchemy was designed as the separate tool and it's not tied to any of frameworks. It is positioned as more powerful ORM rather than Django's.

For startups or MVPs both will do their work ideally. Basic use of both looks pretty much the same.

Jinja2 and Django template engines

Jinja2 is a template engine which was inspired by Django template language. They have the same syntax and rendering structure. From the official Jinja2 docs performance is 10 to 20 times higher than Django. Starting with Django>=1.8 version it's easy to integrate Jinja2 into Django application if there is such need. Both of them provide pretty much the same tools for generating HTML templates which are extremely comfortable.


<title>{% block title %}{% endblock title %}</title>
<ul>
{% for user in users %}
  <li><a href="{{ user.url }}">{{ user.username }}</a></li>
{% endfor %}
</ul>
 

Django Example

Next, we will make one simple task using both frameworks. The task is next: Create endpoint that generates a random password with has given length and sends it in JSON format.

After following Django documentation ‘How to start the project.

You will get something similar to the next structure:


app/
├── app
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── manage.py
└── my_site
    ├── admin.py
    ├── apps.py
    ├── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

Could be really confusing for the first time, right?

This is the basic structure provided by Django. Check up docs for more detailed information.

First of all, we need to create a view function which will be mapped to some URL rule and password generator function which will generate a random string by given length.

Find views.py module in app directory and write down next code:

First two line we import python modules for helping us to generate a random password. According to the task, we have to response in JSON format. Django provides ready to use JsonResponse object from its standard library. To use it we just need to perform import from django.http. There are many different response types provided in Django, for more information read Django docs


import random
import string

from django.http import JsonResponse

def randomword(length=10):
    return ''.join(random.choice(string.ascii_lowercase) for i in range(length))

def generate_password(request, length):
    data = {
        "password": randomword(int(length)),
        "length": length
    }
    return JsonResponse(data)

Function randomword generates a random string of a certain length by the given value (or 10 by default). Next, we create view function which we need to map with URL. Pay attention, Django view function accepts the request object as the first required argument. Also, we added length argument by which will generate our string. Next, we create Python dictionary, which is can be serialized to JSON format perfectly, and generate password inside. As a result, we return JsonResponse object with data we generate in a dictionary.


from django.conf.urls import url
from django.contrib import admin

from my_site.views import generate_password

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    url(r'^gen-pass/(?P<length>\d+)', generate_password),
]

The second step is to register our view function and map it to URL rule. Find urls.py module and write the next code:

Here we import our function that was created before and add url rule inside the urlpatterns list. The first parameter is our URL rule as the regular expression (RE). If you are not familiar with RE check out this.

In our case length can consist only of digits. Example valid URL would look like this: http://127.0.0.1:8000/gen-pass/12 . To run our application go to directory where is manage.py stored and run next command in terminal: $python manage.py runserver

As result, your first Django API would be available by address http://127.0.0.1:8000/gen-pass/12

Flask Example

With help of Flask, the given task could be implemented in one python module:

Looks pretty similar to Django code but with some differences. Let’s check them up.

First, we need to create our Flask application manually creating Flask object. There are many parameters that you can change, for more info check Flask docs . We keep the same password generator function as before with no changes. After we create application, we use its decorator method to register our function. By default, Flask does not support RE in URL rules, but it has few converters as int, string, float, etc.


import random
import string

from flask import Flask, jsonify


app = Flask(__name__)

def randomword(length=10):
   return ''.join(random.choice(string.ascii_lowercase) for i in range(length))


@app.route('/gen-pass/<int:length>/')
def generate_password(length):
    data = {
       "password": randomword(length),
       "length": length
    }
    return jsonify(data)


if __name__ == "__main__":
    app.run()



As you may notice Flask view function does not accept the request as first required argument. The data dictionary generates the same way as before. For creating JSON response Flask provides its own jsonify function which is similar to Django’s JsonResponse. Last two lines say that if we run our app.py module directly from the terminal ($python app.py) it will run the server and our API would be available at http://127.0.0.1:5000/gen-pass/12/.

CONCLUSION

1. If you want to experiment with web application architecture or to take every part under your own control, Flask would be the right choice. In any other case, Django will save your time and efforts providing its own well-designed structure.

2. Having deadlines and high requirements for final product Django is a better choice. Bigger community and more information on Stack Overflow give a chance to find answers faster and easier.

3. If you want to build pure Application Programming Interface (API) without any User Interface (UI) Flask will fit this situation perfectly.

4. Having API and UI in one project is much easier to make it with Django. As Django also provides an amazing REST framework on top of Django application.