Learning To Work With Python Frameworks: FLASK vs DJANGO
Breakdown
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
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
templatesfolder 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_corsand 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
- 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 sqljust gives the module a shorter name. You use it to open the database file (sql.connect("database.db")), create a cursor, run SQL queries withexecute, and save your changes withcommit.
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,UPDATEorDELETE. - 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
SELECTas a list, with each row as a tuple. Use it afterexecutewhen you want the full result set.
Creating a Database Schema
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
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_templatealways looks for HTML files in a folder namedtemplates, 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 asforloops andifstatements, 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
Modelclass (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.pyinto changes in our database. - Running
migrateapplied the migrations foradmin,auth,contenttypesandsessions, which are Django’s built-in apps, along withfirstapp, my own app.
.py Files & Their Responsibilities
/admin, with no extra code. You need to create a superuser first with python manage.py createsuperuser.runserver), create apps (startapp), create and apply database changes (makemigrations and migrate), and more. You rarely edit it, you just run it.schema.sql file from the Flask post, written in Python instead of SQL.SECRET_KEY and the DEBUG flag.path(), and a project-level urls.py can pull in an app’s own routes with include().Creating Two Types of Views: Function-based & Class-based
- A function-based view is a Python function that takes a
requestparameter, which holds the incoming request. - A class-based view is a class that inherits from Django’s
Viewclass, with a method for each HTTP method it handles, such asget()andpost(). - Both return an
HttpResponse.
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 examplepath("about/", views.about). A class-based view goes in asMyView.as_view(). - The project has a main
urls.py. Instead of listing every route there, it can hand off to each app’s ownurls.pywithinclude(), which keeps the routes organised by app.
Django Library
- django.shortcuts / render:
django.shortcutsis a module of helper functions that bundle several steps into one call.renderis 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 anHttpResponse. - django.http / HttpResponse:
django.httpholds the classes for requests and responses.HttpResponseis 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, andrenderreturns one for you. - django.views / View:
django.viewsholds the building blocks for views.Viewis the base class that class-based views inherit from, and you add a method for each HTTP method you want to handle, such asget()andpost(). - django.urls / path:
django.urlshandles URL routing.pathmaps a URL pattern to the view that should run when someone visits it, for examplepath("about/", views.about). - django.contrib / admin:
django.contribis a package of apps that ship with Django.adminis the built-in admin site. You register your models with it inadmin.py, and its URLs are included in your project’surls.py, which gives you a ready-made page for managing your data. - django.db / models:
django.dbis Django’s database layer.modelsprovides the baseModelclass and the field types (CharField,IntegerFieldand 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.methodgives us the HTTP method the user sent, such as GET or POST.request.COOKIESholds the cookies the browser sent, which can help recognise a returning user, andrequest.FILESholds 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=Truestamps the date when the record is first created, andauto_now=Trueupdates it every time the record is saved. For example,created = models.DateField(auto_now_add=True).
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 usespath()inurls.pyto 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, andrender_templateandrenderdo the same job. - Both work with databases. My Flask app used
sqlite3andschema.sql, while Django describes tables inmodels.pyand 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
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.

Comments
Post a Comment