Skip to content

feat: add a daily inspirational quote #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jan 28, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions app/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,11 @@ def __repr__(self):
f'({self.event.owner}'
f'to {self.recipient})>'
)


class Quote(Base):
__tablename__ = "quotes"

id = Column(Integer, primary_key=True, index=True)
text = Column(String, nullable=False)
author = Column(String)
23 changes: 23 additions & 0 deletions app/internal/quotes/daily_quotes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from datetime import date
import random
from typing import Optional

from app.database.models import Quote

from sqlalchemy.orm import Session

TOTAL_DAYS = 366


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
quotes = session.query(Quote).filter(
Quote.id % TOTAL_DAYS == day_num).all()
if len(quotes) > 0:
return random.choice(quotes)
return None
41 changes: 41 additions & 0 deletions app/internal/quotes/load_quotes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import json
from typing import Dict, List

from app.database.models import Quote

from sqlalchemy.orm import Session


def get_quotes_from_json() -> List[Dict]:
"""This function reads all of the daily quotes from a specific JSON file.
The JSON file content is copied from the free API:
'https://type.fit/api/quotes'. I saved the content so the API won't be
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Id suggest adding docs in the Google doc string style https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html
also, there are some typos in the text.
Overall excellent job!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks! :)

called every time the app is initialized."""
try:
with open('app/resources/quotes.json', 'r') as f:
quotes_list = json.load(f)
except (IOError, ValueError):
return []
return quotes_list


def add_quotes_to_db(session: Session) -> None:
"""This function reads the quotes and inserts them into the db"""
all_quotes = get_quotes_from_json()
quotes_objects = [
Quote(text=quote['text'], author=quote['author'])
for quote in all_quotes
]
session.add_all(quotes_objects)
session.commit()


def is_quotes_table_empty(session: Session) -> bool:
return session.query(Quote).count() == 0


def load_daily_quotes(session: Session) -> None:
"""This function loads the daily quotes to the db,
if they weren't already loaden"""
if is_quotes_table_empty(session):
add_quotes_to_db(session)
14 changes: 11 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
from fastapi import FastAPI, Request
from fastapi import Depends, FastAPI, Request
from fastapi.staticfiles import StaticFiles
from sqlalchemy.orm import Session

from app.database import models
from app.database.database import engine
from app.database.database import engine, get_db
from app.dependencies import (
MEDIA_PATH, STATIC_PATH, templates)
from app.internal.quotes import load_quotes, daily_quotes
from app.routers import agenda, event, profile, email, invitation

models.Base.metadata.create_all(bind=engine)
Expand All @@ -13,16 +15,22 @@
app.mount("/static", StaticFiles(directory=STATIC_PATH), name="static")
app.mount("/media", StaticFiles(directory=MEDIA_PATH), name="media")

load_quotes.load_daily_quotes(next(get_db()))

app.include_router(profile.router)
app.include_router(event.router)
app.include_router(agenda.router)
app.include_router(email.router)
app.include_router(invitation.router)


# TODO: I add the quote day to the home page
# until the relavent calendar view will be developed.
@app.get("/")
async def home(request: Request):
async def home(request: Request, db: Session = Depends(get_db)):
quote = daily_quotes.quote_per_day(db)
return templates.TemplateResponse("home.html", {
"request": request,
"message": "Hello, World!",
"quote": quote
})
Loading