Python Django or Flask for web development?

Question:

I have intermediate Python skills and want to learn web development. Should I start with Django or Flask? When I search for answers I only see benefits or downsides of them, but not anyone saying which one is better. And since I don’t have any experience, I cant decide. I know it always comes down to what you want to create etc. But what would you say, is better overall? Is it possible to answer that question?

Asked By: Kelbig

||

Answers:

If you want to make a website quick and easy flask is wonderful due to it’s low entry level, however if you want to learn a framework with more power but a bit confusing django is the clear winner. I personally am using Flask but I think both are good to learn and it might not be as important as you think!

Answered By: Hacker6'x'

As you already have intermediate Python knowledge, starting with Django should be the way to go. I’ve worked with both frameworks and don’t favor one over the other, although I have to say that they are not really that good to compare as their features are, in some parts, very different.

Disclaimer: The provided code snippets are from the official documentation of the Python frameworks and were added just for educational purposes.

Flask

Flask is more suitable for developing APIs rather than real-world user interfaces for the web.

It is a small and lightweight Python web framework that provides useful tools and features, making creating web applications in Python easier. It gives you more flexibility and is a more accessible framework for new developers since you can build a web application quickly using only a single Python file. Flask is also extensible and doesn’t force a particular directory structure or require complicated boilerplate code before getting started.

Having that said, however, Flask doesn’t really compare to Django as many features are missing that make Flask way more suitable for developing backend-heavy applications and services. However, missing these features doesn’t mean that Flask is not a good framework for web development. The two just serve very different needs and goals here. Not having sophisticated feature sets for database migrations, user authentication, or internationalization means you can work on the features you want to implement without worrying about other parts of the framework getting in your way.

Like FastAPI, Flask’s routing system makes it very good for developing RESTful APIs. Extracting data in the request body or headers is straightforward and intuitive

@app.route('/hello')
def hello():
    return 'Hello, World'

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return f'Post {post_id}'

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        return do_the_login()
    else:
        return show_the_login_form()

The problem with Flask serving as a front-end application is that the view system is missing some critical features that would make it a good fit for large-scale single-page applications or websites. In Flask, you need to write your HTML template as-is and cannot benefit from the reusability Django or one of the major Javascript frameworks (like React or Vue) provide. Although, you can use basic features like string interpolation and conditional statements.

@app.route('/hello/')
@app.route('/hello/<name>')
def hello(name=None):
    return render_template('hello.html', name=name)
<!doctype html>
<title>Hello from Flask</title>
{% if name %}
  <h1>Hello {{ name }}!</h1>
{% else %}
  <h1>Hello, World!</h1>
{% endif %}

Flask’s blueprints provide an abstraction of reusable templates, but cannot modulize as much as Django can.

Django

Django is described as a lightweight framework for getting things done, as the official website puts it:

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design.

I’ve worked with Django for the last couple of months for a large enterprise and can confidently say that it is closer to a Javascript-based framework than Flask.

Many of the features Django has can be implemented quickly as the framework has built-in functionality that makes things like user authentication and authorization and database operations (including migrations) very easy to start with.

When it comes to working with a relational database, Django performers great. Defining so-called models, applying and updating those models using migrations is straightforward and easy to start with.

from django.db import models


class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')


class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
$ python manage.py sqlmigrate polls 0001
BEGIN;

CREATE TABLE "polls_question" (
    "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    "question_text" varchar(200) NOT NULL,
    "pub_date" timestamp with time zone NOT NULL
);

CREATE TABLE "polls_choice" (
    "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    "choice_text" varchar(200) NOT NULL,
    "votes" integer NOT NULL,
    "question_id" bigint NOT NULL
);
ALTER TABLE "polls_choice"
  ADD CONSTRAINT "polls_choice_question_id_c5b4b260_fk_polls_question_id"
    FOREIGN KEY ("question_id")
    REFERENCES "polls_question" ("id")
    DEFERRABLE INITIALLY DEFERRED;
CREATE INDEX "polls_choice_question_id_c5b4b260" ON "polls_choice" ("question_id");

COMMIT;

Django has a dedicated HTML template system that works out of the box like any major Javascript framework. Defining reusable components for buttons, forms, popups, table rows, etc. can be done using Django’s HTML inline syntax, which allows you to create for-loops in tables or if statements for conditional behavior and things like that.

Routing in Django is less intuitive than Flask is. The framework provides additional features that are missing in Flask, but make it a more suitable solution for frontend applications that use server-side rendering for processing HTML templates.

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('polls/', include('polls.urls')),
    path('admin/', admin.site.urls),
]

Following the documentation further, you can find a comprehensive page that shows you any feature, concept, or topic Django has to offer.

Besides the development side of things, Django is also equipped with a sophisticated admin site where you or specific users can manage other users. The permission system makes it easy to restrict feature access without getting in the developer’s way.

Django Admin Interface

To summarize, here are the major features Django provides out of the box:

  • Models and Database
  • Interacting with HTTP Services
  • Working with Forms
  • HTML Templates
  • Class-based Views
  • Database Migrations
  • Managing Files
  • Testing
  • User Authentication
  • Caching
  • Localization
  • Logging
  • Pagination
  • Application Administration

Summary

Putting it all together, you can see that Flask and Django are production-grade web frameworks that serve only two distinct use cases. Both frameworks provide extensive routing, logging, and security features. Flask is very good at serving as a backend application, just like a RESTful API does, and Django is more on the user-facing side as it provides dedicated features for reusing HTML templates, user authentication, or internationalization.

I hope this answer helps you find the right framework for your application’s needs.

Answered By: colin

Please check out this article where we have compared top three python web frameworks Django, Flask and FastAPI

Answered By: Rajan Sahu
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.