odapi/database/crud.py

57 lines
1.4 KiB
Python
Raw Normal View History

2020-04-28 20:49:13 +02:00
from datetime import datetime
from app import db
2020-04-28 20:49:13 +02:00
from app.models import *
from app.schema import *
from marshmallow import ValidationError
2020-05-03 00:45:45 +02:00
from pydoc import locate
def insert_data(schema, data):
2020-05-03 00:45:45 +02:00
validate_data(schema=schema, data=data)
model = locate("app.models." + schema)
instance = model(**data)
db.session.add(instance)
db.session.commit()
2020-04-19 21:30:41 +02:00
def delete_data(data):
db.session.delete(data)
db.session.commit()
2020-04-19 21:30:41 +02:00
def save_otp(mobile, otp):
db.session.query(table="Users").filter_by(mobile=mobile).update(dict(otp=otp))
db.session.commit()
def validate_data(schema, data):
2020-05-03 00:45:45 +02:00
schema_name = schema + "Schema"
validation_schema = locate("app.schema." + schema_name)
instance = validation_schema()
try:
2020-05-03 00:45:45 +02:00
instance.load(data)
except ValidationError as err:
print(err.messages)
2020-04-19 21:30:41 +02:00
def fetch_stored_otp(mobile):
user = db.session.query(table="Users").filter_by(mobile=mobile)
otp = user.otp
return otp
2020-05-03 00:45:45 +02:00
def validate_account(mobile):
2020-04-19 21:30:41 +02:00
timestamp = datetime.now()
db.session.query(table="Users").filter_by(mobile=mobile).update(
dict(otp_valid_time=timestamp)
)
2020-05-03 00:45:45 +02:00
db.session.query(table="Users").filter_by(mobile=mobile).update(dict(status=1))
2020-04-19 21:30:41 +02:00
def verify_otp(mobile, otp):
stored_otp = fetch_stored_otp(mobile=mobile)
if stored_otp == otp:
2020-05-03 00:45:45 +02:00
validate_account(mobile=mobile)
2020-04-19 21:30:41 +02:00
return True
return False