Created
October 8, 2020 11:49
-
-
Save davideagle/fef96e90d45ae5e6d124cc6f7c76b6a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# GET /user/1 does not return confirmation | |
# { "id": 1, "email": "davideaglephotos@gmail.com", "username": "jose" } | |
class UserModel(db.Model): | |
__tablename__ = "users" | |
id = db.Column(db.Integer, primary_key=True) | |
username = db.Column(db.String(80), nullable=False, unique=True) | |
password = db.Column(db.String(80), nullable=False) | |
email = db.Column(db.String(80), nullable=False, unique=True) | |
confirmation = db.relationship( | |
"ConfirmationModel", lazy="dynamic", cascade="all, delete-orphan" | |
) | |
@property | |
def most_recent_confirmation(self) -> "ConfirmationModel": | |
# ordered by expiration time (in descending order) | |
return self.confirmation.order_by(db.desc(ConfirmationModel.expire_at)).first() | |
class User(Resource): | |
@classmethod | |
def get(cls, user_id: int): | |
user = UserModel.find_by_id(user_id) | |
if not user: | |
return {"message": USER_NOT_FOUND}, 404 | |
return user_schema.dump(user), 200 | |
class ConfirmationModel(db.Model): | |
__tablename__ = "confirmations" | |
id = db.Column(db.String(50), primary_key=True) | |
expire_at = db.Column(db.Integer, nullable=False) | |
confirmed = db.Column(db.Boolean, nullable=False) | |
user_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) | |
user = db.relationship("UserModel") | |
def __init__(self, user_id: int, **kwargs): | |
super().__init__(**kwargs) | |
self.user_id = user_id | |
self.id = uuid4().hex | |
self.expire_at = int(time()) + CONFIRMATION_EXPIRATION_DELTA | |
self.confirmed = False | |
@classmethod | |
def find_by_id(cls, _id: str) -> "ConfirmationModel": | |
return cls.query.filter_by(id=_id).first() | |
class UserSchema(ma.SQLAlchemyAutoSchema): | |
class Meta: | |
model = UserModel | |
load_only = ("password",) | |
dump_only = ("id", "confirmation") | |
load_instance = True | |
@pre_dump | |
def _pre_dump(self, user: UserModel): | |
user.confirmation = [user.most_recent_confirmation] | |
return user | |
class ConfirmationSchema(ma.SQLAlchemyAutoSchema): | |
class Meta: | |
model = ConfirmationModel | |
load_only = ("user",) | |
dump_only = ("id", "expire_at", "confirmed") | |
include_fk = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment