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.
Adblocker Detected
It looks like you're using an adblocker. Our website relies on ads to keep running. Please consider disabling your adblocker to support us and access the content.
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_URLfrom the environment. - If
DATABASE_URLstarts withpostgres://, it replaces it withpostgresql+psycopg2://. - The
dbinstance is initialized withSQLAlchemy(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
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';Using either method will allow you to view and interact with your PostgreSQL tables on Heroku.