|
| 1 | +"""Class definition for Widget model.""" |
| 2 | +from datetime import datetime, timezone, timedelta |
| 3 | + |
| 4 | +from sqlalchemy.ext.hybrid import hybrid_property |
| 5 | + |
| 6 | +from flask_api_tutorial import db |
| 7 | +from flask_api_tutorial.util.datetime_util import ( |
| 8 | + utc_now, |
| 9 | + format_timedelta_str, |
| 10 | + get_local_utcoffset, |
| 11 | + localized_dt_string, |
| 12 | + make_tzaware, |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +class Widget(db.Model): |
| 17 | + """Widget model for a generic resource in a REST API.""" |
| 18 | + |
| 19 | + __tablename__ = "widget" |
| 20 | + |
| 21 | + id = db.Column(db.Integer, primary_key=True, autoincrement=True) |
| 22 | + name = db.Column(db.String(100), unique=True, nullable=False) |
| 23 | + info_url = db.Column(db.String(255)) |
| 24 | + created_at = db.Column(db.DateTime, default=utc_now) |
| 25 | + deadline = db.Column(db.DateTime) |
| 26 | + |
| 27 | + owner_id = db.Column(db.Integer, db.ForeignKey("site_user.id"), nullable=False) |
| 28 | + owner = db.relationship("User", backref=db.backref("widgets")) |
| 29 | + |
| 30 | + def __repr__(self): |
| 31 | + return f"<Widget name={self.name}, info_url={self.info_url}>" |
| 32 | + |
| 33 | + @hybrid_property |
| 34 | + def created_at_str(self): |
| 35 | + created_at_utc = make_tzaware( |
| 36 | + self.created_at, use_tz=timezone.utc, localize=False |
| 37 | + ) |
| 38 | + return localized_dt_string(created_at_utc, use_tz=get_local_utcoffset()) |
| 39 | + |
| 40 | + @hybrid_property |
| 41 | + def deadline_str(self): |
| 42 | + deadline_utc = make_tzaware(self.deadline, use_tz=timezone.utc, localize=False) |
| 43 | + return localized_dt_string(deadline_utc, use_tz=get_local_utcoffset()) |
| 44 | + |
| 45 | + @hybrid_property |
| 46 | + def deadline_passed(self): |
| 47 | + return datetime.now(timezone.utc) > self.deadline.replace(tzinfo=timezone.utc) |
| 48 | + |
| 49 | + @hybrid_property |
| 50 | + def time_remaining(self): |
| 51 | + time_remaining = self.deadline.replace(tzinfo=timezone.utc) - utc_now() |
| 52 | + return time_remaining if not self.deadline_passed else timedelta(0) |
| 53 | + |
| 54 | + @hybrid_property |
| 55 | + def time_remaining_str(self): |
| 56 | + timedelta_str = format_timedelta_str(self.time_remaining) |
| 57 | + return timedelta_str if not self.deadline_passed else "No time remaining" |
| 58 | + |
| 59 | + @classmethod |
| 60 | + def find_by_name(cls, name): |
| 61 | + return cls.query.filter_by(name=name).first() |
0 commit comments