Featured

Learning To Work With Python Frameworks: FLASK vs DJANGO

 
            Image: https://www.bitcot.com/flask-vs-django/

Breakdown

I had experience building with Python and other APIs, but I’d never worked with a web framework. I wanted to learn how a full-stack web application fits together, so I learned two of the most popular Python ones: Flask first, as the small and simple option, then Django, as the larger one with more built in. This post breaks down what I learned from each, and how they compare.


Tools

  • Python 3.14
  • VS Code
  • Virtual Environments
  • Flask
  • Django


The Use Cases For Each

Flask

  • Built for simple projects, with a small core and a minimal set of features.
  • Easy to install and quick to get started with.
  • Fast and lightweight, but not designed for high-workload projects.
  • Built on a synchronous model, so each worker handles one request at a time. Handling several requests at once means running multiple workers or threads.
  • Best for quick projects and prototyping, like getting a server running fast. Flask’s built-in server is for development only, so production needs a dedicated server in front of it.

Django

  • Built for bigger, more complex projects.
  • Has more features built in, such as an ORM, an admin panel and user authentication.
  • Heavier than Flask, with more overhead, but powerful and able to scale for large projects.
  • Supports both synchronous and asynchronous code. Like Flask, it handles multiple requests at once in production by running multiple workers.
  • Best for large applications. It comes with a lot of settings and configuration built in, so you spend less time wiring things together.


Building With Flask

from flask import Flask, render_template, request
from flask_cors import CORS
from models import create_post, get_posts

Flask Python Library

  • flask: Handles routing (matching URLs to Python functions with @app.route), runs the development server, and ties the rest of the app together.
  • render_template: A function that takes an HTML file from your templates folder and returns it as a page. It uses the Jinja2 templating engine, so you can pass Python variables into the HTML and use loops and conditions inside it.
  • request: An object that holds everything about the incoming request: the method (GET or POST), form data, JSON bodies, URL query parameters and headers. This is how your Python code reads what the browser sent.
  • flask_cors: The extension package (installed as flask-cors) that adds Cross-Origin Resource Sharing support to Flask. It’s a separate install from Flask itself.
  • CORS: The class you import from flask_cors and wrap around your app (CORS(app)). Browsers block a page from calling a server on a different origin (a different domain, port or protocol) unless the server sends permission headers.


Database Library

import sqlite3 as sql
from os import path
  • sqlite3 as sql: Python’s built-in module for working with SQLite, a lightweight database that lives in a single file, with no separate server to install or run. import sqlite3 as sql just gives the module a shorter name. You use it to open the database file (sql.connect("database.db")), create a cursor, run SQL queries with execute, and save your changes with commit.


Flask/HTTP Methods

  • GET: Retrieves data without changing anything. Loading a page or fetching a list of records is a GET request. Any data being sent travels in the URL as query parameters, which you read with request.args.
  • POST: Sends data to the server, usually to create something new, like submitting a form or adding a record to the database. The data travels in the request body, and you read it with request.form.

SQLite Methods

  • connect: Opens the database file and returns a connection object. If the file doesn’t exist yet, SQLite creates it. For example, conn = sql.connect("database.db").
  • cursor: Creates a cursor from the connection. The cursor is the object you use to send commands to the database and read results back, for example cur = conn.cursor().
  • execute: Runs a single SQL statement, such as SELECT, INSERT, UPDATE or DELETE. 
  • commit: Saves the changes you’ve made to the database file. Until you call it, inserts, updates and deletes only exist in the open transaction and are lost if the connection closes.
  • fetchall: Returns every row from the last SELECT as a list, with each row as a tuple. Use it after execute when you want the full result set.


Creating a Database Schema

I started by creating a schema.sql file to define the values that would be stored in the database table. This is where I got to grips with SQL syntax, for example id INTEGER PRIMARY KEY AUTOINCREMENT, which gives every row a unique ID that increases automatically. I then used the schema to generate a database file with SQLite3, and built a server to handle the interactions between the frontend and the database. When a user makes a request from the frontend, the server receives it, grabs the information from the database (the backend) and displays it back to the user.


Creating a Server

#This creates our server object
app = Flask(__name__)

CORS(app)

#Creating routes
@app.route("/", methods=["GET", "POST"])
def index():

    if request.method == "GET":
        pass

    if request.method == "POST":
        name = request.form.get("name")
        post = request.form.get("post")
        create_post(name, post)

    posts = get_posts()

    return render_template("index.html", posts=posts)

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

The server starts with app = Flask(__name__), which creates the application object, and CORS(app) lets a frontend on a different origin make requests to it. I then created a single route at / that accepts both GET and POST requests. A GET request is the browser simply loading the page, so nothing needs to happen there. A POST request is a user submitting the form. The server reads the name and post fields from request.form and passes them to create_post to save them to the database. In both cases, the route finishes the same way: it fetches every post with get_posts() and sends them into index.html with render_template, so the page always shows the latest posts. The last two lines run the development server with debug=True, which reloads the app when the code changes and shows detailed errors in the browser.


Routes & End Points: How They Work Together

An endpoint is the URL that the frontend sends a request to, and a route is the Flask code that decides what happens when that request arrives. In my project, the endpoint is /, and the route tells Flask to run the index function whenever someone visits it with a GET or POST request. The two work as a pair: without the route, the endpoint has nothing behind it, and without the endpoint, the route has no way to be reached. When a user loads the page or submits the form, the request arrives at the endpoint, Flask matches it to the route, the function runs, and whatever it returns is sent back as the response.


Flask & HTML

  • Flask’s render_template always looks for HTML files in a folder named templates, which sits next to the app file.
  • In this project, the HTML page is used to create, get and display posts in the browser.
  • Flask uses the Jinja2 templating engine, which lets you write Python-like logic inside the HTML. Curly braces mark where it goes: {% ... %} for logic such as for loops and if statements, and {{ ... }} for printing a value. Every {% for %} needs a matching {% endfor %} to close it.


Building With Django

Web Framework

  • MVT (Model-View-Template) is the pattern Django uses to organise an app. It explains how the app works and how it interacts with a client.

    • Model: Responsible for the data. It represents how the data is structured, stored and retrieved, and deals with the database part of the application.
    • View: Responsible for user interactions. This is where we take a user’s request, process it, and send back the retrieved data.
    • Template: Deals with the UI and what the user sees.


Creating Models

  • Models are Python classes that inherit from Django’s Model class (models.Model).
  • Each attribute on the class is a field, which becomes a column in the database table.

Forms

  • Forms work in conjunction with models to collect user information and store it.

Migration

  • A migration is the process that converts the changes we make in models.py into changes in our database.
  • Running migrate applied the migrations for admin, auth, contenttypes and sessions, which are Django’s built-in apps, along with firstapp, my own app.


.py Files & Their Responsibilities

admin.py: Registers your models with Django’s built-in admin site. Once a model is registered here, you can add, edit and delete its records through a web page at /admin, with no extra code. You need to create a superuser first with python manage.py createsuperuser.

manage.py: The command-line tool for the project, which sits at the project’s root. It’s how you run the development server (runserver), create apps (startapp), create and apply database changes (makemigrations and migrate), and more. You rarely edit it, you just run it.

models.py: This is the Model in MVT. Each Python class describes a database table, and each attribute on the class is a column. After you change a model, migrations turn that change into real database tables. This is Django’s version of the schema.sql file from the Flask post, written in Python instead of SQL.

settings.py: The project’s central configuration. It lists the installed apps, the database connection, middleware, template locations, static file settings and allowed hosts. It also holds the SECRET_KEY and the DEBUG flag.

urls.py: The URL routing. It maps each URL to the view that should handle it, using path(), and a project-level urls.py can pull in an app’s own routes with include().

views.py: This is the View in MVT. Each view is a function (or class) that takes the user’s request, asks the models for data if it needs any, and returns a response, usually a template filled in with that data.


Creating Two Types of Views: Function-based & Class-based

  • A function-based view is a Python function that takes a request parameter, which holds the incoming request.
  • A class-based view is a class that inherits from Django’s View class, with a method for each HTTP method it handles, such as get() and post().
  • Both return an HttpResponse.
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from .forms import ReservationForm

# Create your views here.
def home(request):
    form = ReservationForm()

    if request.method == 'POST':
        form = ReservationForm (request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse("Reservation successful!")

    return render(request, "index.html", {"form":form})


URL Mapping

  • URL mapping tells Django which view should handle each URL. When a request arrives, Django checks the URL against a list called urlpatterns, from top to bottom, and runs the first view that matches.
  • Each entry uses path(), which takes a URL pattern and the view to run, for example path("about/", views.about). A class-based view goes in as MyView.as_view().
  • The project has a main urls.py. Instead of listing every route there, it can hand off to each app’s own urls.py with include(), which keeps the routes organised by app.
from django.urls import path
from . import views

urlPatterns = [
    path("reservation", views.home),
]


Django Library

from django.shortcuts import render
from django.http import HttpResponse

from django.urls import path
from . import views

from django.contrib import admin

from django.db import models
  • django.shortcuts / render: django.shortcuts is a module of helper functions that bundle several steps into one call. render is the one you’ll use most. It takes the request, the name of a template and a dictionary of data, fills the template with that data, and returns the finished page as an HttpResponse.
  • django.http / HttpResponse: django.http holds the classes for requests and responses. HttpResponse is the object a view sends back to the browser, whether that’s plain text, HTML or something else. It’s what every view must return in the end, and render returns one for you.
  • django.views / View: django.views holds the building blocks for views. View is the base class that class-based views inherit from, and you add a method for each HTTP method you want to handle, such as get() and post().
  • django.urls / path: django.urls handles URL routing. path maps a URL pattern to the view that should run when someone visits it, for example path("about/", views.about).
  • django.contrib / admin: django.contrib is a package of apps that ship with Django. admin is the built-in admin site. You register your models with it in admin.py, and its URLs are included in your project’s urls.py, which gives you a ready-made page for managing your data.
  • django.db / models: django.db is Django’s database layer. models provides the base Model class and the field types (CharField, IntegerField and so on) that you use to describe your database tables as Python classes.


Django Admin Panel

  • The admin panel is a built-in interface with many functions for managing our application, including its data and its users.
  • To use it, we first need to create a superuser.
  • A superuser is an account with all administrative privileges.
  • The panel is divided into Groups and Users, which allows different permissions to be given.
  • Individual users can then be added to different groups.
  • As admin, a superuser has the power to do all of this.


Request & Response Objects

  • Request and response objects are how the user and the application communicate.
  • A request carries information about the user and what they sent.
  • request.method gives us the HTTP method the user sent, such as GET or POST.
  • request.COOKIES holds the cookies the browser sent, which can help recognise a returning user, and request.FILES holds any files uploaded with the request.
  • The response object (HttpResponse) is what we send back to the user.


Some Django Fields

  • CharField: A model field for short pieces of text, like names, titles or usernames. It needs a max_length, which sets the longest value it can hold. For example, name = models.CharField(max_length=100).
  • IntegerField: A model field for whole numbers, such as a score, a quantity or an age. For example, score = models.IntegerField().
  • DateField: A model field for a calendar date (year, month and day, without a time), which appears in Python as a datetime.date. It also has two handy options: auto_now_add=True stamps the date when the record is first created, and auto_now=True updates it every time the record is saved. For example, created = models.DateField(auto_now_add=True).
class Reservation(models.Model):
    firstName = models.CharField(max_length = 255)
    lastName = models.CharField(max_length = 255)
    guestCount = models.IntegerField()
    phoneNo = models.IntegerField()
    reservationTime = models.DateField(auto_now=True)
    comments = models.CharField(max_length = 1000)


SQLite vs MySQL

  • Setup: SQLite is a single file, and it comes with Python, so there’s nothing to install or configure. MySQL is a separate server that you install, run and set up with user accounts and passwords.
  • How it runs: SQLite runs inside your application and reads and writes its file directly. MySQL runs as its own process that your app connects to, which can even be on another machine.
  • Best for: SQLite suits prototypes, small apps and local development. MySQL suits production and larger applications with many users.
  • What they share: Both are relational databases that you query with SQL, so the core ideas (tables, columns, primary keys) carry over from one to the other.


Simlarities Between the Two Frameworks

  • Both route URLs to Python code. Flask uses @app.route() above a function, while Django uses path() in urls.py to point at a view.
  • Both use request and response objects. The request tells you what the user sent, including the HTTP method (GET or POST), and your code sends a response back.
  • Both render HTML templates with very similar syntax. {% for %} and {% endfor %} are used for logic, and {{ }} for printing values, and render_template and render do the same job.
  • Both work with databases. My Flask app used sqlite3 and schema.sql, while Django describes tables in models.py and uses SQLite by default. Django can also be configured to use a MySQL database instead, and in both cases your Python code reads and writes the data and passes it into a template.


What I Learned

Django has more to learn up front (and felt a bit overwhelming), but it comes with a lot already set up, which is why it suits larger projects, while Flask is still the quicker choice for a small prototype. Moving from Flask to Django showed me how much a framework can do for you. In Flask, I wired everything together myself, and it felt I manage as a first time user. Django splits those jobs between the MVT pieces: models for the data, views for handling requests, and templates for what the user sees. Each lives in its own file, from models.py and views.py to urls.py and settings.py. Having to jump to each of those modules to do certain things felt overwhelming (like I didn't know what I was doing. At some point, I just started thinking about it like building a plugin and managing all those pieces to one system. I'll need to build a bit more with Django to lock in the concepts and get comfortable.


Conclusion

Learning Django after Flask showed me two sides of web development. Flask taught me how the pieces fit together by making me wire them up myself. Django showed me what a full framework handles for you: models that become database tables, views and URL mapping that route requests, templates for what the user sees, and an admin panel that works as soon as a model is registered. Flask is great for quick prototypes and small projects, and Django is better for larger applications that need more built in. I’m still learning Django, and there’s plenty left to explore, but knowing both gives me a better sense of which one to reach for next time.

Comments