Before setting up the environment, ensure you have the following installed:
- Python (>=3.7): Download Python
- Virtual Environment: Comes built-in with Python (
venv). - Node.js (Optional): Required if using TailwindCSS or other frontend tools.
- Database System (Optional): PostgreSQL, MySQL, or SQLite (default).
mkdir flask_sqlalchemy_project
cd flask_sqlalchemy_projectpython -m venv venvActivate the virtual environment:
- On Windows:
.\venv\Scripts\activate
- On Mac/Linux:
source venv/bin/activate
pip install Flask Flask-SQLAlchemy Flask-MigrateOptional tools:
pip install psycopg2-binary # For PostgreSQL
pip install mysql-connector-python # For MySQLTo freeze dependencies for version control:
pip freeze > requirements.txtmkdir app
cd appCreate the initial files:
touch __init__.py models.py routes.pySample directory structure:
flask_sqlalchemy_project/
├── venv/
├── requirements.txt
├── app/
│ ├── __init__.py
│ ├── models.py
│ └── routes.py
Create a .env file in the root directory:
FLASK_APP=app
FLASK_ENV=development
DATABASE_URL=sqlite:///database.db
SECRET_KEY=supersecretkey
Install python-dotenv to load environment variables:
pip install python-dotenvUpdate __init__.py to load environment variables:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from dotenv import load_dotenv
import os
load_dotenv()
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL')
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY')
# Initialize extensions
db = SQLAlchemy(app)Create a main.py at the root level:
from app import app
if __name__ == '__main__':
app.run(debug=True)Run the application:
flask runInstall TailwindCSS using Node.js:
npm install -D tailwindcss
npx tailwindcss initConfigure the input/output paths in tailwind.config.js, and watch for changes:
npx tailwindcss -i ./static/css/tailwind.css -o ./static/css/output.css --watch- Keep secrets secure using environment variables.
- Freeze and track dependencies with
requirements.txt. - Separate configuration logic into a
config.pyfile for better maintainability. - Use version control systems like Git for collaboration.
Now you're all set up to start building a Flask-SQLAlchemy project!