Skip to content

Commit 1d8bdf5

Browse files
authored
Bugfix/cleanup2 (#291)
1 parent ea15719 commit 1d8bdf5

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+1545
-998
lines changed

app/config.py.example

+2-2
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,12 @@ CALENDAR_HOME_PAGE = "calendar.pythonic.guru"
7272
# link to the application registration page
7373
CALENDAR_REGISTRATION_PAGE = r"calendar.pythonic.guru/registration"
7474

75-
# import
75+
# IMPORT
7676
MAX_FILE_SIZE_MB = 5 # 5MB
7777
VALID_FILE_EXTENSION = (".txt", ".csv", ".ics") # Can import only these files.
7878
# Events must be within 20 years range from the current year.
7979
EVENT_VALID_YEARS = 20
80-
EVENT_HEADER_NOT_EMPTY = 1 # 1- for not empty, 0- for empty.
80+
EVENT_HEADER_NOT_EMPTY = True
8181
EVENT_HEADER_LIMIT = 50 # Max characters for event header.
8282
EVENT_CONTENT_LIMIT = 500 # Max characters for event content.
8383
MAX_EVENTS_START_DATE = 10 # Max Events with the same start date.

app/database/models.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,15 +20,15 @@
2020
)
2121
from sqlalchemy.dialects.postgresql import TSVECTOR
2222
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
23-
from sqlalchemy.ext.declarative.api import declarative_base
23+
from sqlalchemy.ext.declarative.api import declarative_base, DeclarativeMeta
2424
from sqlalchemy.orm import relationship, Session
2525
from sqlalchemy.sql.schema import CheckConstraint
2626

2727
from app.config import PSQL_ENVIRONMENT
2828
from app.dependencies import logger
2929
import app.routers.salary.config as SalaryConfig
3030

31-
Base = declarative_base()
31+
Base: DeclarativeMeta = declarative_base()
3232

3333

3434
class User(Base):

app/internal/astronomy.py

+55-47
Original file line numberDiff line numberDiff line change
@@ -1,70 +1,78 @@
1-
import datetime
1+
from datetime import datetime
22
import functools
3-
from typing import Dict
3+
from typing import Any, Dict
44

55
import httpx
66

77
from app import config
88

9-
# This feature requires an API KEY - get yours free @ www.weatherapi.com
9+
# This feature requires an API key. Get yours free at www.weatherapi.com.
10+
ASTRONOMY_URL = "https://api.weatherapi.com/v1/astronomy.json"
11+
NO_API_RESPONSE = _("No response from server.")
1012

11-
ASTRONOMY_URL = "http://api.weatherapi.com/v1/astronomy.json"
12-
NO_API_RESPONSE = "No response from server"
1313

14+
async def get_astronomical_data(
15+
date: datetime, location: str
16+
) -> Dict[str, Any]:
17+
"""Returns astronomical data (sun and moon) for date and location.
1418
15-
@functools.lru_cache(maxsize=128, typed=False)
16-
async def get_data_from_api(formatted_date: str, location: str) \
17-
-> Dict[str, int]:
18-
""" get the relevant astronomical data by calling the "weather api" API.
1919
Args:
20-
formatted_date (date) - relevant date.
21-
location (str) - location name.
20+
date: The requested date for astronomical data.
21+
location: The location name.
22+
23+
Returns:
24+
A dictionary with the following entries:
25+
success: True or False.
26+
error: The error description.
27+
location: A dictionary of relevant data, including:
28+
name, region, country, lat, lon etc.
29+
astronomy: A dictionary of relevant data, including:
30+
sunrise, sunset, moonrise, moonset, moon_phase, and
31+
moon_illumination.
32+
"""
33+
formatted_date = date.strftime('%Y-%m-%d')
34+
return await _get_astronomical_data_from_api(formatted_date, location)
35+
36+
37+
@functools.lru_cache(maxsize=128)
38+
async def _get_astronomical_data_from_api(
39+
date: str, location: str
40+
) -> Dict[str, Any]:
41+
"""Returns astronomical_data from a Weather API call.
42+
43+
Args:
44+
date: The requested date for astronomical data.
45+
location: The location name.
46+
2247
Returns:
23-
response_json (json dict) including:
24-
relevant part (data / error) of the JSON returned by the API.
25-
Success (bool)
26-
ErrorDescription (str) - error message.
48+
A dictionary with the results from the API call.
2749
"""
28-
input_query_string = {'key': config.ASTRONOMY_API_KEY, 'q': location,
29-
'dt': formatted_date}
30-
output = {}
50+
input_query_string = {
51+
'key': config.ASTRONOMY_API_KEY,
52+
'q': location,
53+
'dt': date,
54+
}
55+
56+
output: Dict[str, Any] = {}
3157
try:
3258
async with httpx.AsyncClient() as client:
33-
response = await client.get(ASTRONOMY_URL,
34-
params=input_query_string)
59+
response = await client.get(
60+
ASTRONOMY_URL, params=input_query_string)
3561
except httpx.HTTPError:
36-
output["Success"] = False
37-
output["ErrorDescription"] = NO_API_RESPONSE
62+
output["success"] = False
63+
output["error"] = NO_API_RESPONSE
3864
return output
65+
3966
if response.status_code != httpx.codes.OK:
40-
output["Success"] = False
41-
output["ErrorDescription"] = NO_API_RESPONSE
67+
output["success"] = False
68+
output["error"] = NO_API_RESPONSE
4269
return output
43-
output["Success"] = True
70+
71+
output["success"] = True
4472
try:
4573
output.update(response.json()['location'])
4674
return output
4775
except KeyError:
48-
output["Success"] = False
49-
output["ErrorDescription"] = response.json()['error']['message']
76+
output["success"] = False
77+
output["error"] = response.json()['error']['message']
5078
return output
51-
52-
53-
async def get_astronomical_data(requested_date: datetime.datetime,
54-
location: str) -> Dict[str, int]:
55-
""" get astronomical data (Sun & Moon) for date & location -
56-
main function.
57-
Args:
58-
requested_date (date) - date requested for astronomical data.
59-
location (str) - location name.
60-
Returns: dictionary with the following entries:
61-
Status - success / failure.
62-
ErrorDescription - error description (relevant only in case of error).
63-
location - relevant location values(relevant only in case of success).
64-
name, region, country, lat, lon etc.
65-
astronomy - relevant astronomy values, all time in local time -
66-
(relevant only in case of success):
67-
sunrise, sunset, moonrise, moonset, moon_phase, moon_illumination.
68-
"""
69-
formatted_date = requested_date.strftime('%Y-%m-%d')
70-
return await get_data_from_api(formatted_date, location)

app/internal/celebrity.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,5 @@
22

33

44
def get_today_month_and_day() -> str:
5-
"""Get today's month and day - %m-%d"""
6-
5+
"""Returns today's month and day in the format: %m-%d"""
76
return datetime.date.today().strftime("%m-%d")

app/internal/daily_quotes.py

+30-13
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,39 @@
99
TOTAL_DAYS = 366
1010

1111

12-
def create_quote_object(quotes_fields: Dict[str, Optional[str]]) -> Quote:
13-
"""This function create a quote object from given fields dictionary.
14-
It is used for adding the data from the json into the db"""
12+
def get_quote(quote_: Dict[str, Optional[str]]) -> Quote:
13+
"""Returns a Quote object from the dictionary data.
14+
15+
Args:
16+
quote_: A dictionary quote related information.
17+
18+
Returns:
19+
A new Quote object.
20+
"""
1521
return Quote(
16-
text=quotes_fields['text'],
17-
author=quotes_fields['author']
22+
text=quote_['text'],
23+
author=quote_['author'],
1824
)
1925

2026

21-
def quote_per_day(
22-
session: Session, date: date = date.today()
27+
def get_quote_of_day(
28+
session: Session, requested_date: date = date.today()
2329
) -> Optional[Quote]:
24-
"""This function provides a daily quote, relevant to the current
25-
day of the year. The quote is randomally selected from a set
26-
of quotes matching to the given day"""
27-
day_num = date.timetuple().tm_yday
28-
quote = session.query(Quote).filter(
29-
Quote.id % TOTAL_DAYS == day_num).order_by(func.random()).first()
30+
"""Returns the Quote object for the specific day.
31+
32+
The quote is randomly selected from a set of quotes matching the given day.
33+
34+
Args:
35+
session: The database connection.
36+
requested_date: Optional; The requested date.
37+
38+
Returns:
39+
A Quote object.
40+
"""
41+
day_number = requested_date.timetuple().tm_yday
42+
quote = (session.query(Quote)
43+
.filter(Quote.id % TOTAL_DAYS == day_number)
44+
.order_by(func.random())
45+
.first()
46+
)
3047
return quote

0 commit comments

Comments
 (0)