Configuring Database URI
Your database connection is configured via:
SQLALCHEMY_DATABASE_URISQLALCHEMY_DATABASE_URI
SQLite (easy for learning)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///app.db"Meaning:
- store the database file
app.dbapp.dbin your project directory
Postgres (common in production)
A typical URI format:
postgresql://username:password@host:port/database_namepostgresql://username:password@host:port/database_name
Example:
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://myuser:mypassword@localhost:5432/mydb"app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://myuser:mypassword@localhost:5432/mydb"Security best practice
Never hardcode passwords in code.
Use environment variables:
import os
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")import os
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")A note about DATABASE_URL formats
Some platforms provide DATABASE_URLDATABASE_URL like:
postgres://...postgres://...
SQLAlchemy expects postgresql://...postgresql://....
You may need to normalize it depending on your deployment platform.
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
