-
Notifications
You must be signed in to change notification settings - Fork 52
Expand file tree
/
Copy pathdaily_quotes.py
More file actions
46 lines (36 loc) · 1.5 KB
/
daily_quotes.py
File metadata and controls
46 lines (36 loc) · 1.5 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
from datetime import date
from typing import Dict, Optional
from app.database.models import Quote, UserQuotes
from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import func
TOTAL_DAYS = 366
def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote:
"""This function create a quote object from given fields dictionary.
It is used for adding the data from the json into the db"""
return Quote(
text=quotes_fields['text'],
author=quotes_fields['author'],
is_favorite=False
)
def quote_per_day(
session: Session, date: date = date.today()
) -> Optional[Quote]:
"""This function provides a daily quote, relevant to the current
day of the year. The quote is randomally selected from a set
of quotes matching to the given day"""
day_num = date.timetuple().tm_yday
quote = session.query(Quote).filter(
Quote.id % TOTAL_DAYS == day_num).order_by(func.random()).first()
return quote
def get_quotes(session, user_id):
"""Retrieves the users' favorite quotes from the database."""
quotes = []
user_quotes = session.query(UserQuotes).filter_by(user_id=user_id).all()
for user_quote in user_quotes:
quote = session.query(Quote).filter_by(id=user_quote.quote_id).first()
quote.is_favorite = True
quotes.append(quote)
return quotes
def get_quote_id(session, quote):
"""Retrieve quote id given the text of the quote."""
return session.query(Quote).filter_by(text=quote).first().id