Skip to content

Commit 00450c3

Browse files
committed
fix: many code improvements
1 parent d1da1f3 commit 00450c3

File tree

5 files changed

+88
-103
lines changed

5 files changed

+88
-103
lines changed

app/internal/locations.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import requests
2-
from typing import Dict
1+
from typing import Any, Dict, Optional
32

3+
import requests
44
from sqlalchemy.orm import Session
55

66
from app.database.models import Location
@@ -16,39 +16,43 @@ def create_location_object(location_: Dict[str, str]) -> Location:
1616
A new Location object.
1717
"""
1818
return Location(
19-
country=location_['country'],
20-
city=location_['city'],
21-
zip_number=location_['zip_number'],
19+
country=location_["country"],
20+
city=location_["city"],
21+
zip_number=location_["zip_number"],
2222
)
2323

2424

25-
def return_zip_to_location(session: Session) -> str:
26-
"""Returns the zip number of the user IP location that match location object.
25+
def return_zip_to_location(session: Session) -> Optional[str]:
26+
"""Returns the zip number of the user IP location that match location
27+
object.
2728
2829
Args:
2930
session: The database connection.
3031
3132
Returns:
3233
A zip number for the user location.
3334
"""
34-
ip_and_location = requests.get('http://ipinfo.io/json').json()
35+
response = requests.get("http://ipinfo.io/json").json()
36+
if not response.ok:
37+
return None
3538
for location in session.query(Location).all():
36-
if (location.city == ip_and_location['city']) and \
37-
(location.country == ip_and_location['country']):
39+
if (location.city == response["city"]
40+
and location.country == response["country"]):
3841
return location.zip_number
3942

4043

41-
def get_user_location(session: Session) -> str:
44+
def get_user_location(session: Session) -> Optional[Dict[str, Any]]:
4245
"""Returns the user location.
4346
4447
Args:
4548
session: The database connection.
4649
4750
Returns:
48-
A user location string.
51+
A user location.
4952
"""
5053
my_location = return_zip_to_location(session)
51-
location_details = requests.get(
54+
response = requests.get(
5255
f"https://www.hebcal.com/shabbat?cfg=json&geonameid={my_location}"
5356
)
54-
return location_details.json()
57+
if response.ok:
58+
return response.json()

app/internal/shabbat.py

Lines changed: 32 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,44 +1,46 @@
1-
from typing import Dict, Optional, Union
2-
from datetime import datetime
3-
4-
5-
def shabbat_time_by_user_location(
6-
shabbat_time: Dict[str, str]
7-
) -> Dict[str, Union[str, datetime]]:
8-
"""Returns the shabbat time of the user location..
9-
10-
Args:
11-
Shabbat details.
12-
13-
Returns:
14-
Shabbat start end ending time.
15-
"""
16-
shabbat_limit = {
17-
'start_hour': shabbat_time['items'][5]['title'].split(': ')[1],
18-
'start_date': datetime.strptime(
19-
shabbat_time['items'][5]['date'].split('T')[0], "%Y-%m-%d"
20-
).date(),
21-
'end_hour': shabbat_time['items'][7]['title'].split(': ')[1],
22-
'end_date': datetime.strptime(
23-
shabbat_time['items'][7]['date'].split('T')[0], "%Y-%m-%d"
24-
).date()}
25-
return shabbat_limit
1+
from datetime import date, datetime
2+
from typing import Any, Dict, Optional, Union
263

274

285
def get_shabbat_if_date_friday(
29-
shabbat_time: Dict[str, str],
30-
date: datetime
31-
) -> Optional[Dict[str, Union[str, datetime]]]:
6+
shabbat_time: Dict[str, Any],
7+
calendar_date: date,
8+
) -> Optional[Dict[str, Union[str, date]]]:
329
"""Returns shabbat start end ending time if specific date
3310
is Saturday, else None.
3411
3512
Args:
36-
Shabbat details and date.
13+
shabbat_time: Shabbat details.
14+
calendar_date: date.
3715
3816
Returns:
3917
Shabbat start end ending time if specific date
4018
is Saturday, else None
4119
"""
4220
shabbat_obj = shabbat_time_by_user_location(shabbat_time)
43-
if date == shabbat_obj['start_date']:
21+
if calendar_date == shabbat_obj["start_date"]:
4422
return shabbat_obj
23+
24+
25+
def shabbat_time_by_user_location(
26+
shabbat_time: Dict[str, Any]
27+
) -> Dict[str, Union[str, date]]:
28+
"""Returns the shabbat time of the user location..
29+
30+
Args:
31+
shabbat_time: Shabbat details.
32+
33+
Returns:
34+
Shabbat start end ending time.
35+
"""
36+
shabbat_entry = shabbat_time["items"][5]
37+
shabbat_exit = shabbat_time["items"][7]
38+
shabbat_entry_date = shabbat_entry["date"].split("T")[0]
39+
shabbat_exit_date = shabbat_entry["date"].split("T")[0]
40+
shabbat_limit = {
41+
"start_hour": shabbat_entry["title"].split(": ")[1],
42+
"start_date": datetime.strptime(shabbat_entry_date, "%Y-%m-%d").date(),
43+
"end_hour": shabbat_exit["title"].split(": ")[1],
44+
"end_date": datetime.strptime(shabbat_exit_date, "%Y-%m-%d").date(),
45+
}
46+
return shabbat_limit

app/routers/dayview.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44

55
from fastapi import APIRouter, Depends, HTTPException, Request
66

7-
from app.database.models import Event, User
7+
from app.database.models import Event
88
from app.dependencies import get_db, templates
99
from app.internal import international_days, locations, shabbat, zodiac
1010
from app.internal.security.dependencies import current_user
11+
from app.internal.security.schema import CurrentUser
1112
from app.routers.user import get_all_user_events
1213

1314
router = APIRouter()
@@ -191,7 +192,7 @@ async def dayview(
191192
date: str,
192193
view="day",
193194
session=Depends(get_db),
194-
user: User = Depends(current_user),
195+
user: CurrentUser = Depends(current_user),
195196
):
196197
try:
197198
day = datetime.strptime(date, "%Y-%m-%d")
@@ -211,10 +212,10 @@ async def dayview(
211212
current_time_with_attrs = CurrentTimeAttributes(date=day)
212213
inter_day = international_days.get_international_day_per_day(session, day)
213214
location_and_shabbat = locations.get_user_location(session)
214-
location = location_and_shabbat['location']['title']
215+
location = location_and_shabbat["location"]["title"]
215216
shabbat_obj = shabbat.get_shabbat_if_date_friday(
216217
location_and_shabbat,
217-
day.date()
218+
day.date(),
218219
)
219220
month = day.strftime("%B").upper()
220221
return templates.TemplateResponse(

tests/fixtures/location_fixture.py

Lines changed: 0 additions & 34 deletions
This file was deleted.

tests/test_shabbat.py

Lines changed: 33 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,28 +2,40 @@
22

33
from app.internal import shabbat
44

5-
SHABBAT_TIME = {'items': [
6-
{'title': 'Fast begins'},
7-
{'title': "Ta'anit Esther"},
8-
{'title': 'Fast ends'},
9-
{'title': 'Erev Purim'},
10-
{'title': 'Purim'},
11-
{'title': 'Candle lighting: 17:15',
12-
'date': '2021-02-26T17:15:00+02:00',
13-
'category': 'candles',
14-
'title_orig': 'Candle lighting',
15-
'hebrew': 'הדלקת נרות'},
16-
{'title': 'Parashat Tetzaveh'},
17-
{'title': 'Havdalah: 18:11',
18-
'date': '2021-02-27T18:11:00+02:00',
19-
'category': 'havdalah',
20-
'title_orig': 'Havdalah',
21-
'hebrew': 'הבדלה'}
22-
]}
23-
DATE1 = date(2021, 2, 27)
24-
FRIDAY = date(2021, 2, 27)
5+
SHABBAT_TIME = {
6+
"items":
7+
[
8+
{"title": "Fast begins"},
9+
{"title": "Ta'anit Esther"},
10+
{"title": "Fast ends"},
11+
{"title": "Erev Purim"},
12+
{"title": "Purim"},
13+
{
14+
"title": "Candle lighting: 17:15",
15+
"date": "2021-02-26T17:15:00+02:00",
16+
"category": "candles",
17+
"title_orig": "Candle lighting",
18+
"hebrew": "הדלקת נרות",
19+
},
20+
{"title": "Parashat Tetzaveh"},
21+
{
22+
"title": "Havdalah: 18:11",
23+
"date": "2021-02-27T18:11:00+02:00",
24+
"category": "havdalah",
25+
"title_orig": "Havdalah",
26+
"hebrew": "הבדלה",
27+
},
28+
]
29+
}
30+
BAD_DAY = date(2021, 2, 27)
31+
FRIDAY = date(2021, 2, 26)
2532

2633

2734
def test_return_none_if_date_no_friday():
28-
result = shabbat.get_shabbat_if_date_friday(SHABBAT_TIME, DATE1)
35+
result = shabbat.get_shabbat_if_date_friday(SHABBAT_TIME, BAD_DAY)
2936
assert result is None
37+
38+
39+
def test_return_if_date_is_friday():
40+
result = shabbat.get_shabbat_if_date_friday(SHABBAT_TIME, FRIDAY)
41+
assert result

0 commit comments

Comments
 (0)