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()

Create a 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 into database

user = User('bob', 'password')
db.session.add(user)
db.session.commit()
Clone this wiki locally