covot/database/crud.py

59 lines
1.4 KiB
Python
Raw Normal View History

2020-11-17 14:16:44 +01:00
from sqlalchemy import or_
2020-11-25 13:44:07 +01:00
from sqlalchemy.orm import Query
2020-11-17 14:16:44 +01:00
from database import SessionLocal, engine, models
from database.models import Users
db = SessionLocal()
2020-11-25 13:44:07 +01:00
def search_database(id) -> Query:
"""
Returns the user associated with the id argument
"""
2020-11-17 14:16:44 +01:00
return db.query(Users).filter(
or_(Users.correo_institucional == id, Users.numero_de_documento == id)
)
2020-11-25 13:44:07 +01:00
def insert_data(data) -> None:
"""
Inserts a new user into the database
"""
2020-11-17 14:16:44 +01:00
item = Users(**data)
db.add(item)
db.commit()
db.refresh(item)
2020-11-25 13:44:07 +01:00
def create_database(data) -> None:
"""
Creates the SQL database from scratch and populates it
"""
2020-11-17 14:16:44 +01:00
models.Base.metadata.create_all(bind=engine)
existing_row = search_database(data["correo_institucional"])
if existing_row:
return
insert_data(data)
2020-11-25 11:06:38 +01:00
2020-11-25 13:44:07 +01:00
def save_attribute(attribute, data) -> None:
"""
Updates the attribute value with the content of data
"""
2020-11-25 11:06:38 +01:00
key = eval("Users." + attribute)
db.query(Users).filter(
or_(Users.correo_institucional == id, Users.numero_de_documento == id)
).update({key: data})
2020-11-25 13:44:07 +01:00
def verify_code(id, code) -> bool:
"""
Verifies that two-factor authentification code matches the database record
"""
2020-11-25 11:06:38 +01:00
db_record = search_database(id=id)
valid_code = code == db_record
if valid_code:
return True
return False