Skip to content

Commit bc93f38

Browse files
committed
Merge branch 'develop' of https://github.com/PythonFreeCourse/calendar into feature/delete-event
2 parents 95e8e79 + 5762677 commit bc93f38

File tree

14 files changed

+6776
-16
lines changed

14 files changed

+6776
-16
lines changed

app/database/models.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,11 @@ def __repr__(self):
108108
f'({self.event.owner}'
109109
f'to {self.recipient})>'
110110
)
111+
112+
113+
class Quote(Base):
114+
__tablename__ = "quotes"
115+
116+
id = Column(Integer, primary_key=True, index=True)
117+
text = Column(String, nullable=False)
118+
author = Column(String)

app/internal/quotes/daily_quotes.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from datetime import date
2+
from typing import Optional
3+
4+
from app.database.models import Quote
5+
6+
from sqlalchemy.orm import Session
7+
from sqlalchemy.sql.expression import func
8+
9+
TOTAL_DAYS = 366
10+
11+
12+
def quote_per_day(
13+
session: Session, date: date = date.today()
14+
) -> Optional[Quote]:
15+
"""This function provides a daily quote, relevant to the current
16+
day of the year. The quote is randomally selected from a set
17+
of quotes matching to the given day"""
18+
day_num = date.timetuple().tm_yday
19+
quote = session.query(Quote).filter(
20+
Quote.id % TOTAL_DAYS == day_num).order_by(func.random()).first()
21+
return quote

app/internal/quotes/load_quotes.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import json
2+
from typing import Dict, List, Optional
3+
4+
from app.database.models import Quote
5+
6+
from sqlalchemy.orm import Session
7+
8+
9+
def get_quotes_from_json() -> List[Dict[str, Optional[str]]]:
10+
"""This function reads all of the daily quotes from a specific JSON file.
11+
The JSON file content is copied from the free API:
12+
'https://type.fit/api/quotes'. I saved the content so the API won't be
13+
called every time the app is initialized."""
14+
try:
15+
with open('app/resources/quotes.json', 'r') as f:
16+
quotes_list = json.load(f)
17+
except (IOError, ValueError):
18+
return []
19+
return quotes_list
20+
21+
22+
def add_quotes_to_db(session: Session) -> None:
23+
"""This function reads the quotes and inserts them into the db"""
24+
all_quotes = get_quotes_from_json()
25+
quotes_objects = [
26+
Quote(text=quote['text'], author=quote['author'])
27+
for quote in all_quotes
28+
]
29+
session.add_all(quotes_objects)
30+
session.commit()
31+
32+
33+
def is_quotes_table_empty(session: Session) -> bool:
34+
return session.query(Quote).count() == 0
35+
36+
37+
def load_daily_quotes(session: Session) -> None:
38+
"""This function loads the daily quotes to the db,
39+
if they weren't already loaden"""
40+
if is_quotes_table_empty(session):
41+
add_quotes_to_db(session)

app/main.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
1-
from fastapi import FastAPI, Request
1+
from fastapi import Depends, FastAPI, Request
22
from fastapi.staticfiles import StaticFiles
3+
from sqlalchemy.orm import Session
34

45
from app.config import PSQL_ENVIRONMENT
56
from app.database import models
6-
from app.database.database import engine
7+
from app.database.database import engine, get_db
78
from app.dependencies import (
89
MEDIA_PATH, STATIC_PATH, templates)
10+
from app.internal.quotes import load_quotes, daily_quotes
911
from app.routers import (
1012
agenda, dayview, email, event, invitation, profile, search, telegram,
1113
whatsapp
@@ -31,6 +33,8 @@ def create_tables(engine, psql_environment):
3133
app.mount("/static", StaticFiles(directory=STATIC_PATH), name="static")
3234
app.mount("/media", StaticFiles(directory=MEDIA_PATH), name="media")
3335

36+
load_quotes.load_daily_quotes(next(get_db()))
37+
3438
# Configure logger
3539
logger = LoggerCustomizer.make_logger(config.LOG_PATH,
3640
config.LOG_FILENAME,
@@ -40,7 +44,6 @@ def create_tables(engine, psql_environment):
4044
config.LOG_FORMAT)
4145
app.logger = logger
4246

43-
4447
app.include_router(profile.router)
4548
app.include_router(event.router)
4649
app.include_router(agenda.router)
@@ -54,10 +57,14 @@ def create_tables(engine, psql_environment):
5457
telegram_bot.set_webhook()
5558

5659

60+
# TODO: I add the quote day to the home page
61+
# until the relavent calendar view will be developed.
5762
@app.get("/")
5863
@app.logger.catch()
59-
async def home(request: Request):
64+
async def home(request: Request, db: Session = Depends(get_db)):
65+
quote = daily_quotes.quote_per_day(db)
6066
return templates.TemplateResponse("home.html", {
6167
"request": request,
6268
"message": "Hello, World!",
69+
"quote": quote
6370
})

0 commit comments

Comments
 (0)