Share:
Hi all,
I’m developing a web application using Flask and I want to integrate SQLAlchemy for database management. Can someone provide a step-by-step guide on setting up a Flask application with SQLAlchemy, including models and database migrations?
Hide Responses
Hi,
To set up a Flask application with SQLAlchemy:
pip install Flask SQLAlchemy
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
@app.route('/')
def hello():
return "Hello, World!"
if __name__ == '__main__':
app.run(debug=True)
flask shell
>>> from app import db
>>> db.create_all()
>>> from app import User
>>> user = User(username='testuser')
>>> db.session.add(user)
>>> db.session.commit()
pip install Flask-Migrate
Update app.py
:
from flask_migrate import Migrate
migrate = Migrate(app, db)
Initialize and run migrations:
flask db init
flask db migrate -m "Initial migration."
flask db upgrade
This setup provides a basic Flask application integrated with SQLAlchemy for database management.
Emily Parker
9 months ago