Skip to content

SQLAlchemy

Rajesh Khadka edited this page Nov 20, 2019 · 3 revisions

We will be using the SQLAlchemy as an ORM

SQLAlchemy Configuration

  1. Install the SQLalchemy
pip install flask-sqlalchemy
pip install psycopg2
  1. Add configuration on run.py
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://<user>:<password>@localhost/database_name'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  1. Initialize the SqlAlchemy
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()
db.init_app(app)

@app.before_first_request
def create_tables():
    db.create_all()

Database Model

class User(db.Model):
    id = db.Column(db.String(), primary_key=True)
    username = db.Column(db.String())
    password = db.Column(db.String())

Insert

user = User('bob', 'password')
db.session.add(user)
db.session.commit()

Query

users = User.query.all()

Filter

user = User.query.filter(User.id == '5519fae8-52d2-4c75-9207-01a944309143')

Delete

 user = User.query.filter(User.id == user_id).first()
 db.session.delete(user)
 db.session.commit()

Update

user = User.query.filter(User.id == user_id).first()
if user:
   user.username = data['username']
   user.password = data['password']
   db.session.commit()

Commit contains the changes made in our previous code with the implementation of the database: