In this tutorial, you'll learn how to build a web application using the Flask framework and PostgreSQL as the database. We'll cover the entire process, from setting up your environment to deploying your application.


Prerequisites

  • Python Installed: Ensure Python 3.x is installed on your system.
  • Pip Package Manager: Ensure pip is installed for managing Python packages.
  • PostgreSQL: Install PostgreSQL and set up a database for your application.
  • Basic Python and SQL Knowledge: Familiarity with Python and SQL basics will be helpful.

Step 1: Set Up Your Development Environment

Create a Virtual Environment


python -m venv venv

Activate the Virtual Environment

  • Windows:

.\venv\Scripts\activate
  • macOS/Linux:

source venv/bin/activate

Install Required Packages

Install Flask, SQLAlchemy, and psycopg2 for PostgreSQL integration.


pip install Flask SQLAlchemy psycopg2-binary

Step 2: Create a Basic Flask Application

Create the Project Structure


mkdir flask_app
cd flask_app

Create the Flask Application

Create a file named app.py and add the following code:


from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://username:password@localhost:5432/mydatabase'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return f''

@app.route('/')
def index():
    users = User.query.all()
    return render_template('index.html', users=users)

@app.route('/add', methods=['POST'])
def add_user():
    username = request.form['username']
    email = request.form['email']
    new_user = User(username=username, email=email)
    db.session.add(new_user)
    db.session.commit()
    return redirect(url_for('index'))

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

Create HTML Template

Create a directory named templates and add a file named index.html:





    
    
    Flask App


    

User List

    {% for user in users %}
  • {{ user.username }} - {{ user.email }}
  • {% endfor %}

Add User


Step 3: Set Up PostgreSQL

Create a Database

Log in to your PostgreSQL instance and run:


CREATE DATABASE mydatabase;

Create a Database User


CREATE USER myuser WITH PASSWORD 'mypassword';
GRANT ALL PRIVILEGES ON DATABASE mydatabase TO myuser;

Update Database URI

In app.py, replace:


'username:password@localhost:5432/mydatabase'

with your actual database connection details.


Step 4: Initialize the Database

Create the Database Tables

Open a Python shell in the project directory and run:


from app import db
db.create_all()

Start the Flask Application


python app.py

Access the Application

Go to http://127.0.0.1:5000/ in your web browser. You should see the user list and a form to add new users.


Step 5: Perform CRUD Operations

  • Create: Add new users using the form.
  • Read: View users on the homepage.
  • Update and Delete: Extend the app with routes/templates to support these actions.

Step 6: Deploy the Application

Choose a Hosting Platform

Use services like Heroku, AWS, or Google Cloud to host your Flask app.

Prepare for Deployment

Create a Procfile and requirements.txt.

Procfile:


web: python app.py

requirements.txt:


Flask
SQLAlchemy
psycopg2-binary
gunicorn

Deploy

Follow your chosen platform’s instructions to deploy your app.


Conclusion

In this tutorial, you built a basic web application using Flask and PostgreSQL. You learned how to:

  • Set up your development environment
  • Connect Flask with PostgreSQL via SQLAlchemy
  • Perform basic CRUD operations
  • Prepare your app for deployment

For further improvements, consider adding authentication, input validation, and advanced queries. You can also deploy with Docker for enhanced portability.