Building a Basic Website with Flask and SQLAlchemy

A Quick Tutorial for Creating a Bare Minimum Backend

Andrew Udell
Level Up Coding
Published in
11 min readJul 16, 2021

--

Photo by Glenn Carstens-Peters on Unsplash

Flask is a lightweight and incredibly flexible framework for creating website backends in Python. In addition to abstracting difficult web concepts, such as routing, rendering HTML documents, and handling static files, it’s easy to integrate with any of Python’s many libraries.

To show its power, this tutorial will develop a simple website to maintain movies and their IMDb ratings. This website will be a CRUD, which stands for create, read, update, and delete, which are the basic operations of a database. This serves as a good introduction as nearly every website is, at its most basic form, a CRUD. Even giants, such as Facebook and YouTube, are still recording and altering records in databases.

Since database operations will be performed, SQLAlchemy will be used. Designated as toolkit and Object Relational Mapper (ORM), this library will allow the database to be directly modified by Python code instead of writing raw SQL. While this tutorial will use SQLite for demonstration, much of the code can be adapted to much more scalable database, such as MySQL or PostgreSQL, with little modification.

Setting up the Database

Before using any other part of the backend is created, a database needs to be initialized. To keep things organized, make a directory called “Project” and within it, create a subdirectory called “MovieDB,” as shown below:

Project
├──MovieDB

Within the MovieDB directory, create a Python file called “SetupDB.py”. This will be the file we use to set up the database.

# Imports
from sqlalchemy import Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine

The first few lines of this file will import the mandatory components of the SQLAlchemy library.

# Pass a declarative base and create a object to correspond with a table in the database
Base = declarative_base()

class Movie(Base):

__tablename__ = 'movie'
movie_id = Column(Integer, primary_key=True)…

--

--