top

DJANGO vs FLASK (a comparative study)

Introduction Choosing a better tool before you start building your own web application is one of the most important steps in the whole development process. Web frameworks have been around to make the jobs easier for the programmer for quite a long time, but being so many in number, they often put beginners in dilemma. Where on one hand, they give users a lot of option to choose from for developing their projects, they often tend to put the programmer in a dilemma when it comes to narrow down the final choice to just one. In this blog post, I'm gonna help you out in choosing a framework better suited to your needs. We will mainly be talking here about Django and Flask, but the selection criteria can be applied to other frameworks available in the market as well like Diesel, Tornado, Bottle etc too. We will start with trying to make a hello world program using both Django and Flask in tandem, this will be followed by trying to know how templating works in them and after that, we will delve into technical differences between the ways the two frameworks function.   Table of Contents Bootstrapping in Flask Bootstrapping in Django Templating in Django Compulsory Parameters Optional Parameters Templating in Flask Comparison   1. Bootstrapping in Flask A simple hello world program in flask looks somewhat like this: And that's it, we are done. Run this program from your terminal and browse to localhost:8000 and you will be greeted by the hello world message. That's the beauty of flask, it's quick, simple and also provides the user freedom to choose how the objects will be treated. (Okay! I will revisit the last point again.)   2. Bootstrapping in Django Now we write a Hello World program in Django. Run the following commands in your terminal $ django-admin startproject HelloWorld $ cd HelloWorld You will obtain the following directory structure. . ├── HelloWorld │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py └── manage.py 1 directory, 5 files The "__init__.py" file basically tells python compiler that the particular directory is to be treated like a module. The "settings.py" file holds the configuration information of the web app like the database engine being used, the apps present in our web server etc. The "urls.py" file is like the index table file. It holds the information about the how the pages will be displayed once the user visits a particular sub-url. The next step is to start an application inside the web server. To do this run the following command. $ django-admin startapp HelloWorldApp You will obtain the following directory structure. . ├── HelloWorld │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── HelloWorldApp │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── manage.py 3 directories, 12 files Here there are two files of our interest. One is "views.py"; it will contain the logic of requests and response. And the second one is "models.py"; this file will contain the database information. The core code writing part will be a three-step process: STEP 1: Changing the views.py file.  It should look somewhat like this: STEP 2: Making an entry in the urls.py file. We need to tell the compiler that on visiting a particular url, the corresponding file must be displayed. STEP 3: Adding our app to the settings.py file. We will have to add our HelloWorldApp to the list of installed apps in the settings.py file. Make necessary changes to the file where the tuple with the name INSTALLED_APPS is located and edit it so that the final tuple looks like this. That's almost it, now switch to terminal and run the following command $ python manage.py runserver Now visit the url "http://localhost:8000/HelloWorldApp/" and you will be greeted by a hello world message. At this stage, you might feel that compared to the flask, writing a simple hello world program in Django is a little overkill. Moving on! Till now we have seen how to we can render simple texts using both Django and Flask. But frequently we will come across situations where you will need to display a webpage with contents being generated dynamically. This is called Templating. Templating allows you to juxtapose your HTML and CSS codes together so that you can provide beautiful pages with required data being generated on the fly.   3. Templating in Django Django handles templating by providing "Django-Template Language" (DTL). DTL mainly relies on the Render function. The Render function takes in six parameters. Two compulsory and four optional. 3.1 Compulsory Parameters: Request: The object used to generate the response. template_name: The location of your HTML template file to be loaded is given here. You can give multiple files here, in that case, Django will look for the first match and load it. 3.2 Optional Parameters: context: A key and value pairs (dictionary in python) of values to be inserted in the dictionary. Default value null. content_type: The MIME type used for the resulting document. status: The status code for the response. Default value is 200 using: The NAME of the template engine used to render the template A simple example to use templating in Django. We will display the date and time using Django in this case. STEP 1: We will need to create an HTML page (template.html). STEP 2: Change the views.py to add the following function. That's it. This is how you use templating in Django. The additional options can be used according to your need. I took a simple example just to give you a gist of it.   4. Templating in Flask Flask uses Jinja 2 engine to render the templates and uses the function render_template to instead of render function in Django. Here all we have to do to is to pass the template name along with the list of variables we are gonna use in our template. The signature of a render_template function looks somewhat like this:  render_template("template_name.html", {"key1"="variable1", "key2"="variable2"...}) The second argument is a dictionary of key and value pair just like in the case of templating in Django. Now let's take a look at a sample code on how templating works in Flask. We will try to display the values of three variables in a table. It will just be a two-step process. STEP 1: Create a file flask_template.py: STEP 2: Create an HTML template to render the files (values.html). And viola! you're done. Visit "http://127.0.0.1:5000/template" and you will see the required variables displayed.   5. Comparison Now! If you are still here with me then till now we have seen how to write hello world programs in both Django and Flask followed by how to execute basic templating operations using both the mentioned framework. Till now you must have noticed that the number of files created in case of Django was more than the total number of files created in Flask. Yeah, well that's where I'm gonna start telling you about the three major points where Django and Flask contrast with each other in the way they perform. 1. Django provides you with a ton of additional stuff that you may not have asked for, in case of your small projects, like an admin panel. Flask on the other hand "does as it is told", nothing more, nothing less. Django, along with an admin panel also includes Database interface, an Object Relation Model whether you need it or not. These features make Django an ideal choice when the user needs to develop for the production environment. This brings us to the second point. 2. Flask provides you more control over how exactly you want the objects to be treated and the way things should be implemented. Flask is simple, flexible and as Gareth Dwyer says in his blog, provides fine-grained control. For learners, this is often a boon because at any point of time in the development cycle you have only those components which you require and know. 3. The community size. Whenever we start learning anything new, we are bound to get trapped, stuck in some doubts or the other. This event also occurs after the learning curve is complete and the user is actually using the tool to develop something new. We rush around asking for suggestions, solutions on sites like StackOverflow etc. That's when the existing community size of the framework plays a critical role. Django has been around for over 11 years now and if what we have seen so far, is something to go by, then you can say that Django will continue to be one of the top choices for a foreseeable future. Flask is quite new and doesn't have as much as community support as Django. Finally, my personal opinion says that if you are new to the web development world, both are equally good, but I might just inch a bit in favour of Flask because of its simplicity and at any moment of time there won't be any files lying around whose task you don't know. In case you're going for a fully fledged production environment, Django will lift much load off your shoulders.
Rated 4.0/5 based on 0 customer reviews
Normal Mode Dark Mode

DJANGO vs FLASK (a comparative study)

Devershi Chandra
Blog
19th Feb, 2018
DJANGO vs FLASK (a comparative study)

Introduction

Choosing a better tool before you start building your own web application is one of the most important steps in the whole development process. Web frameworks have been around to make the jobs easier for the programmer for quite a long time, but being so many in number, they often put beginners in dilemma. Where on one hand, they give users a lot of option to choose from for developing their projects, they often tend to put the programmer in a dilemma when it comes to narrow down the final choice to just one. In this blog post, I'm gonna help you out in choosing a framework better suited to your needs. We will mainly be talking here about Django and Flask, but the selection criteria can be applied to other frameworks available in the market as well like Diesel, Tornado, Bottle etc too.

We will start with trying to make a hello world program using both Django and Flask in tandem, this will be followed by trying to know how templating works in them and after that, we will delve into technical differences between the ways the two frameworks function.

 

Table of Contents

  1. Bootstrapping in Flask

  2. Bootstrapping in Django

  3. Templating in Django

    1. Compulsory Parameters

    2. Optional Parameters

  4. Templating in Flask

  5. Comparison

 

1. Bootstrapping in Flask

A simple hello world program in flask looks somewhat like this:

And that's it, we are done. Run this program from your terminal and browse to localhost:8000 and you will be greeted by the hello world message.

That's the beauty of flask, it's quick, simple and also provides the user freedom to choose how the objects will be treated. (Okay! I will revisit the last point again.)

 

2. Bootstrapping in Django

Now we write a Hello World program in Django. Run the following commands in your terminal

$ django-admin startproject HelloWorld

$ cd HelloWorld

You will obtain the following directory structure.

.
├── HelloWorld
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py

1 directory, 5 files

The "__init__.py" file basically tells python compiler that the particular directory is to be treated like a module. The "settings.py" file holds the configuration information of the web app like the database engine being used, the apps present in our web server etc. The "urls.py" file is like the index table file. It holds the information about the how the pages will be displayed once the user visits a particular sub-url.

The next step is to start an application inside the web server. To do this run the following command.

$ django-admin startapp HelloWorldApp

You will obtain the following directory structure.

.
├── HelloWorld
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
├── HelloWorldApp
│ ├── admin.py
│ ├── apps.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
└── manage.py

3 directories, 12 files

Here there are two files of our interest. One is "views.py"; it will contain the logic of requests and response. And the second one is "models.py"; this file will contain the database information.

The core code writing part will be a three-step process:

STEP 1: Changing the views.py file. 

It should look somewhat like this:

STEP 2: Making an entry in the urls.py file.

We need to tell the compiler that on visiting a particular url, the corresponding file must be displayed.

STEP 3: Adding our app to the settings.py file.

We will have to add our HelloWorldApp to the list of installed apps in the settings.py file. Make necessary changes to the file where the tuple with the name INSTALLED_APPS is located and edit it so that the final tuple looks like this.

That's almost it, now switch to terminal and run the following command

$ python manage.py runserver

Now visit the url "http://localhost:8000/HelloWorldApp/" and you will be greeted by a hello world message.

At this stage, you might feel that compared to the flask, writing a simple hello world program in Django is a little overkill. Moving on!

Till now we have seen how to we can render simple texts using both Django and Flask. But frequently we will come across situations where you will need to display a webpage with contents being generated dynamically. This is called Templating.

Templating allows you to juxtapose your HTML and CSS codes together so that you can provide beautiful pages with required data being generated on the fly.

 

3. Templating in Django

Django handles templating by providing "Django-Template Language" (DTL). DTL mainly relies on the Render function.

The Render function takes in six parameters. Two compulsory and four optional.

3.1 Compulsory Parameters:

  • Request: The object used to generate the response.

  • template_name: The location of your HTML template file to be loaded is given here. You can give multiple files here, in that case, Django will look for the first match and load it.

3.2 Optional Parameters:

  • context: A key and value pairs (dictionary in python) of values to be inserted in the dictionary. Default value null.

  • content_type: The MIME type used for the resulting document.

  • status: The status code for the response. Default value is 200

  • using: The NAME of the template engine used to render the template

A simple example to use templating in Django.

We will display the date and time using Django in this case.

STEP 1: We will need to create an HTML page (template.html).

STEP 2: Change the views.py to add the following function.

That's it. This is how you use templating in Django. The additional options can be used according to your need. I took a simple example just to give you a gist of it.

 

4. Templating in Flask

Flask uses Jinja 2 engine to render the templates and uses the function render_template to instead of render function in Django. Here all we have to do to is to pass the template name along with the list of variables we are gonna use in our template.

The signature of a render_template function looks somewhat like this: 

render_template("template_name.html", {"key1"="variable1", "key2"="variable2"...})

The second argument is a dictionary of key and value pair just like in the case of templating in Django.

Now let's take a look at a sample code on how templating works in Flask.

We will try to display the values of three variables in a table. It will just be a two-step process.

STEP 1: Create a file flask_template.py:

STEP 2Create an HTML template to render the files (values.html).

And viola! you're done. Visit "http://127.0.0.1:5000/template" and you will see the required variables displayed.

 

5. Comparison

Now! If you are still here with me then till now we have seen how to write hello world programs in both Django and Flask followed by how to execute basic templating operations using both the mentioned framework. Till now you must have noticed that the number of files created in case of Django was more than the total number of files created in Flask.

Yeah, well that's where I'm gonna start telling you about the three major points where Django and Flask contrast with each other in the way they perform.

1. Django provides you with a ton of additional stuff that you may not have asked for, in case of your small projects, like an admin panel. Flask on the other hand "does as it is told", nothing more, nothing less. Django, along with an admin panel also includes Database interface, an Object Relation Model whether you need it or not. These features make Django an ideal choice when the user needs to develop for the production environment. This brings us to the second point.

2. Flask provides you more control over how exactly you want the objects to be treated and the way things should be implemented. Flask is simple, flexible and as Gareth Dwyer says in his blog, provides fine-grained control. For learners, this is often a boon because at any point of time in the development cycle you have only those components which you require and know.

3. The community size. Whenever we start learning anything new, we are bound to get trapped, stuck in some doubts or the other. This event also occurs after the learning curve is complete and the user is actually using the tool to develop something new. We rush around asking for suggestions, solutions on sites like StackOverflow etc. That's when the existing community size of the framework plays a critical role. Django has been around for over 11 years now and if what we have seen so far, is something to go by, then you can say that

Django will continue to be one of the top choices for a foreseeable future. Flask is quite new and doesn't have as much as community support as Django.

Finally, my personal opinion says that if you are new to the web development world, both are equally good, but I might just inch a bit in favour of Flask because of its simplicity and at any moment of time there won't be any files lying around whose task you don't know. In case you're going for a fully fledged production environment, Django will lift much load off your shoulders.

Devershi

Devershi Chandra

Blog Author
Devershi Chandra is a Cyber Security undergrad student, born and raised in the northern plains of India. A coder by the day and quoran by night, Devershi takes interest in developing applications, primarily aimed at making lives easier for people. When not writing blogs in his free time, he can be found learning new frameworks and languages. Devershi also enjoys playing role-playing games and having long conversations on any topic under the sun and beyond, over a beer.

Leave a Reply

Your email address will not be published. Required fields are marked *

SUBSCRIBE OUR BLOG

Follow Us On

Share on

other Blogs

20% Discount