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
2020-11-25 18:21:22 +01:00
from database.models import User
2020-11-17 14:16:44 +01:00
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-25 18:21:22 +01:00
return db.query(User).filter(
or_(User.correo_institucional == id, User.numero_de_documento == id)
2020-11-17 14:16:44 +01:00
)
2020-11-25 13:44:07 +01:00
def insert_data(data) -> None:
"""
Inserts a new user into the database
"""
2020-11-25 18:21:22 +01:00
item = User(**data)
2020-11-17 14:16:44 +01:00
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 18:21:22 +01:00
key = eval("User." + attribute)
db.query(User).filter(
or_(User.correo_institucional == id, User.numero_de_documento == id)
2020-11-25 11:06:38 +01:00
).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