DeveloperBreeze

Postgresql Development Tutorials, Guides & Insights

Unlock 2+ expert-curated postgresql tutorials, real-world code snippets, and modern dev strategies. From fundamentals to advanced topics, boost your postgresql skills on DeveloperBreeze.

Configuring SQLAlchemy with PostgreSQL on Heroku: A Quick Guide

Code November 08, 2024
python

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os

app = Flask(__name__)

# Adjust the DATABASE_URL format for SQLAlchemy compatibility
database_url = os.getenv("DATABASE_URL", "")
if database_url.startswith("postgres://"):
    database_url = database_url.replace("postgres://", "postgresql+psycopg2://")

app.config["SQLALCHEMY_DATABASE_URI"] = database_url

# Initialize the SQLAlchemy object
db = SQLAlchemy(app)

# Sample route to test the setup
@app.route("/")
def index():
    return "Database URI setup complete!"

if __name__ == "__main__":
    app.run()
  • This code retrieves the DATABASE_URL from the environment.
  • If DATABASE_URL starts with postgres://, it replaces it with postgresql+psycopg2://.
  • The db instance is initialized with SQLAlchemy(app) for use with SQLAlchemy ORM.
  • The replacement of "postgres://" with "postgresql+psycopg2://" is necessary because of a compatibility issue between the URI format provided by Heroku and the URI format expected by SQLAlchemy.

How to view tables on a PostgreSQL database hosted on Heroku

Tutorial November 06, 2024

Replace <your-app-name> with the name of your Heroku application.

Once connected to the database, you can list all tables with: