-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathdaily_quotes.py
More file actions
72 lines (55 loc) · 1.72 KB
/
daily_quotes.py
File metadata and controls
72 lines (55 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
from datetime import date
from typing import Dict, List, Optional
from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import func
from app.database.models import Quote, UserQuotes
TOTAL_DAYS = 366
def get_quote(quote_: Dict[str, Optional[str]]) -> Quote:
"""Returns a Quote object from the dictionary data.
Args:
quote_: A dictionary quote related information.
Returns:
A new Quote object.
"""
return Quote(
text=quote_["text"],
author=quote_["author"],
is_favorite=False,
)
def get_quote_of_day(
session: Session,
requested_date: date = date.today(),
) -> Optional[Quote]:
"""Returns the Quote object for the specific day.
The quote is randomly selected from a set of quotes matching the given day.
Args:
session: The database connection.
requested_date: Optional; The requested date.
Returns:
A Quote object.
"""
day_number = requested_date.timetuple().tm_yday
quote = (
session.query(Quote)
.filter(Quote.id % TOTAL_DAYS == day_number)
.order_by(func.random())
.first()
)
return quote
def get_quotes(session: Session, user_id: int) -> List[Quote]:
"""Retrieves the users' favorite quotes from the database."""
return session.query(Quote).filter_by(id=UserQuotes.quote_id).all()
def is_quote_favorite(
session: Session,
user_id: int,
quote_of_day: Quote,
) -> bool:
"""Checks if the daily quote is in favorites list."""
if not quote_of_day:
return False
exists = (
session.query(UserQuotes)
.filter(user_id == user_id, UserQuotes.quote_id == quote_of_day.id)
.scalar()
)
return bool(exists)