Skip to content

feat: Add zodiac signs to the day & month view + refactor json data loader #155

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
Feb 5, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
19 changes: 19 additions & 0 deletions app/database/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,22 @@ class Quote(Base):
id = Column(Integer, primary_key=True, index=True)
text = Column(String, nullable=False)
author = Column(String)


class Zodiac(Base):
__tablename__ = "zodiac-signs"

id = Column(Integer, primary_key=True, index=True)
name = Column(String, nullable=False)
start_month = Column(Integer, nullable=False)
start_day_in_month = Column(Integer, nullable=False)
end_month = Column(Integer, nullable=False)
end_day_in_month = Column(Integer, nullable=False)

def __repr__(self):
return (
f'<Zodiac '
f'{self.name} '
f'{self.start_day_in_month}/{self.start_month}-'
f'{self.end_day_in_month}/{self.end_month}>'
)
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from datetime import date
from typing import Optional
from typing import Dict, Optional

from app.database.models import Quote

Expand All @@ -9,6 +9,15 @@
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']
)


def quote_per_day(
session: Session, date: date = date.today()
) -> Optional[Quote]:
Expand Down
57 changes: 57 additions & 0 deletions app/internal/json_data_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import json
import os
from typing import Dict, List, Callable, Union

from loguru import logger
from sqlalchemy.orm import Session

from app.database.database import Base
from app.database.models import Quote, Zodiac
from app.internal import daily_quotes, zodiac


def get_data_from_json(path: str) -> List[Dict[str, Union[str, int, None]]]:
"""This function reads all of the data from a specific JSON file.
The json file consists of list of dictionaries"""
try:
with open(path, 'r') as f:
json_content_list = json.load(f)
except (IOError, ValueError):
file_name = os.path.basename(path)
logger.exception(
f"An error occurred during reading of json file: {file_name}")
return []
return json_content_list


def is_table_empty(session: Session, table: Base) -> bool:
return session.query(table).count() == 0


def load_data(
session: Session, path: str,
table: Base, object_creator_function: Callable) -> None:
"""This function loads the specific data to the db,
if it wasn't already loaded"""
if not is_table_empty(session, table):
return None
json_objects_list = get_data_from_json(path)
objects = [
object_creator_function(json_object)
for json_object in json_objects_list]
session.add_all(objects)
session.commit()


def load_to_db(session) -> None:
"""This function loads all the data for features
based on pre-defind json data"""
load_data(
session, 'app/resources/zodiac.json',
Zodiac, zodiac.create_zodiac_object)
load_data(
session, 'app/resources/quotes.json',
Quote, daily_quotes.create_quote_object)
"""The quotes JSON file content is copied from the free API:
'https://type.fit/api/quotes'. I saved the content so the API won't be
called every time the app is initialized."""
41 changes: 0 additions & 41 deletions app/internal/quotes/load_quotes.py

This file was deleted.

42 changes: 42 additions & 0 deletions app/internal/zodiac.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from datetime import date
from typing import Dict, Union

from sqlalchemy.orm import Session
from sqlalchemy import and_, or_

from app.database.models import Zodiac


def create_zodiac_object(zodiac_fields: Dict[str, Union[str, int]]) -> Zodiac:
"""This function create a zodiac object from given fields dictionary.
It is used for adding the data from the json into the db"""
return Zodiac(
name=zodiac_fields['name'],
start_month=zodiac_fields['start_month'],
start_day_in_month=zodiac_fields['start_day_in_month'],
end_month=zodiac_fields['end_month'],
end_day_in_month=zodiac_fields['end_day_in_month']
)


def get_zodiac_of_day(session: Session, date: date) -> Zodiac:
"""This function return a zodiac object
according to the current day."""
first_month_of_sign_filter = and_(
Zodiac.start_month == date.month,
Zodiac.start_day_in_month <= date.day)
second_month_of_sign_filter = and_(
Zodiac.end_month == date.month,
Zodiac.end_day_in_month >= date.day)
zodiac_obj = session.query(Zodiac).filter(
or_(first_month_of_sign_filter, second_month_of_sign_filter)).first()
return zodiac_obj


# TODO: Call this function from the month view
def get_zodiac_of_month(session: Session, date: date) -> Zodiac:
"""This function return a zodiac object
according to the current month."""
zodiac_obj = session.query(Zodiac).filter(
Zodiac.end_month == date.month).first()
return zodiac_obj
4 changes: 2 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from app.database import models
from app.database.database import engine, get_db
from app.dependencies import (logger, MEDIA_PATH, STATIC_PATH, templates)
from app.internal.quotes import daily_quotes, load_quotes
from app.internal import daily_quotes, json_data_loader
from app.routers import (
agenda, dayview, email, event, invitation, profile, search, telegram,
whatsapp
Expand All @@ -30,7 +30,7 @@ def create_tables(engine, psql_environment):
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()))
json_data_loader.load_to_db(next(get_db()))

app.logger = logger

Expand Down
86 changes: 86 additions & 0 deletions app/resources/zodiac.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
[
{
"name": "Capricorn",
"start_month": 12,
"start_day_in_month": 22,
"end_month": 1,
"end_day_in_month": 19
},
{
"name": "Aquarius",
"start_month": 1,
"start_day_in_month": 20,
"end_month": 2,
"end_day_in_month": 18
},
{
"name": "Pisces",
"start_month": 2,
"start_day_in_month": 19,
"end_month": 3,
"end_day_in_month": 20
},
{
"name": "Aries",
"start_month": 3,
"start_day_in_month": 21,
"end_month": 4,
"end_day_in_month": 19
},
{
"name": "Taurus",
"start_month": 4,
"start_day_in_month": 20,
"end_month": 5,
"end_day_in_month": 20
},
{
"name": "Gemini",
"start_month": 5,
"start_day_in_month": 21,
"end_month": 6,
"end_day_in_month": 20
},
{
"name": "Cancer",
"start_month": 6,
"start_day_in_month": 21,
"end_month": 7,
"end_day_in_month": 22
},
{
"name": "Leo",
"start_month": 7,
"start_day_in_month": 23,
"end_month": 8,
"end_day_in_month": 22
},
{
"name": "Virgo",
"start_month": 8,
"start_day_in_month": 23,
"end_month": 9,
"end_day_in_month": 22
},
{
"name": "Libra",
"start_month": 9,
"start_day_in_month": 23,
"end_month": 10,
"end_day_in_month": 22
},
{
"name": "Scorpio",
"start_month": 10,
"start_day_in_month": 23,
"end_month": 11,
"end_day_in_month": 21
},
{
"name": "Sagittarius",
"start_month": 11,
"start_day_in_month": 22,
"end_month": 12,
"end_day_in_month": 21
}
]
5 changes: 4 additions & 1 deletion app/routers/dayview.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from app.database.database import get_db
from app.database.models import Event, User
from app.dependencies import TEMPLATES_PATH
from app.internal import zodiac

templates = Jinja2Templates(directory=TEMPLATES_PATH)

Expand Down Expand Up @@ -104,9 +105,11 @@ async def dayview(request: Request, date: str, db_session=Depends(get_db)):
and_(Event.end >= day, Event.end < day_end),
and_(Event.start < day_end, day_end < Event.end)))
events_n_attrs = [(event, DivAttributes(event, day)) for event in events]
zodiac_obj = zodiac.get_zodiac_of_day(db_session, day)
return templates.TemplateResponse("dayview.html", {
"request": request,
"events": events_n_attrs,
"month": day.strftime("%B").upper(),
"day": day.day
"day": day.day,
"zodiac": zodiac_obj
})
13 changes: 13 additions & 0 deletions app/static/dayview.css
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,16 @@ html {
.action-continer:hover .action-icon {
visibility: visible;
}

.zodiac-sign {
position: fixed;
right: 1.2em;
top: 1.6em;
padding-right: 0.4em;
padding-left: 0.4em;
padding-bottom: 0.2em;
border: solid 0.1px var(--primary);
background-color: var(--borders-variant);
border-radius:50px;
box-shadow: 1px 1px 2px #999;
}
28 changes: 28 additions & 0 deletions app/static/images/zodiac/Aquarius.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 28 additions & 0 deletions app/static/images/zodiac/Aries.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions app/static/images/zodiac/Cancer.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading