-
Notifications
You must be signed in to change notification settings - Fork 1
SQLAlchemy
Rajesh Khadka edited this page Nov 20, 2019
·
3 revisions
We will be using the SQLAlchemy as an ORM
- Install the SQLalchemy
pip install flask-sqlalchemy
pip install psycopg2
- Add configuration on run.py
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://<user>:<password>@localhost/database_name'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
- Initialize the SqlAlchemy
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
db.init_app(app)
@app.before_first_request
def create_tables():
db.create_all()
class User(db.Model):
id = db.Column(db.String(), primary_key=True)
username = db.Column(db.String())
password = db.Column(db.String())
user = User('bob', 'password')
db.session.add(user)
db.session.commit()
users = User.query.all()
user = User.query.filter(User.id == '5519fae8-52d2-4c75-9207-01a944309143')
user = User.query.filter(User.id == user_id).first()
db.session.delete(user)
db.session.commit()
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: