-
Notifications
You must be signed in to change notification settings - Fork 52
/
event.py
830 lines (721 loc) · 24.8 KB
/
event.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
import io
import json
import urllib
from datetime import datetime as dt
from operator import attrgetter
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
from fastapi import APIRouter, Depends, File, HTTPException, Request
from PIL import Image
from pydantic import BaseModel
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from sqlalchemy.sql.elements import Null
from starlette import status
from starlette.datastructures import ImmutableMultiDict
from starlette.responses import RedirectResponse, Response
from starlette.templating import _TemplateResponse
from app.config import PICTURE_EXTENSION
from app.database.models import (
Category,
Comment,
Country,
Event,
SharedList,
SharedListItem,
User,
UserEvent,
)
from app.dependencies import UPLOAD_PATH, get_db, logger, templates
from app.internal import comment as cmt
from app.internal.emotion import get_emotion
from app.internal.event import (
get_all_countries_names,
get_invited_emails,
get_location_coordinates,
get_messages,
get_uninvited_regular_emails,
raise_if_zoom_link_invalid,
)
from app.internal.privacy import PrivacyKinds
from app.internal.security.dependencies import current_user
from app.internal.utils import create_model, get_current_user, save
from app.routers.categories import get_user_categories
IMAGE_HEIGHT = 200
EVENT_DATA = Tuple[Event, List[Dict[str, str]], str]
TIME_FORMAT = "%Y-%m-%d %H:%M"
START_FORMAT = "%A, %d/%m/%Y %H:%M"
UPDATE_EVENTS_FIELDS = {
"title": str,
"start": dt,
"end": dt,
"availability": bool,
"all_day": bool,
"is_google_event": bool,
"content": (str, type(None)),
"location": (str, type(None)),
"vc_link": (str, type(None)),
"category_id": (int, type(None)),
}
router = APIRouter(
prefix="/event",
tags=["event"],
responses={404: {"description": "Not found"}},
)
class SharedItem(NamedTuple):
name: str
amount: float
participant: str
class EventModel(BaseModel):
title: str
start: dt
end: dt
content: str
owner_id: int
location: str
is_google_event: bool
@router.get("/")
async def get_events(session=Depends(get_db)):
return session.query(Event).all()
@router.post("/")
async def create_event_api(event: EventModel, session=Depends(get_db)):
create_event(
db=session,
title=event.title,
start=event.start,
end=event.end,
content=event.content,
owner_id=event.owner_id,
location=event.location,
is_google_event=event.is_google_event,
)
return {"success": True}
def get_categories_list(
user: User,
db_session: Session = Depends(get_db),
) -> List[Category]:
return get_user_categories(db_session, user.user_id)
@router.get("/edit", include_in_schema=False)
async def eventedit(
request: Request,
db_session: Session = Depends(get_db),
user: User = Depends(current_user),
) -> Response:
countries_names = get_all_countries_names(db_session)
categories_list = get_categories_list(user, db_session)
return templates.TemplateResponse(
"eventedit.html",
{
"request": request,
"categories_list": categories_list,
"privacy": PrivacyKinds,
"countries_names": countries_names,
},
)
@router.post("/edit", include_in_schema=False)
async def create_new_event(
request: Request,
event_img: bytes = File(None),
session=Depends(get_db),
) -> Response:
data = await request.form()
title = data["title"]
content = data["description"]
start = dt.strptime(
data["start_date"] + " " + data["start_time"],
TIME_FORMAT,
)
end = dt.strptime(data["end_date"] + " " + data["end_time"], TIME_FORMAT)
owner_id = get_current_user(session).id
availability = data.get("availability", "True") == "True"
location = data["location"]
all_day = data["event_type"] and data["event_type"] == "on"
vc_link = data.get("vc_link")
category_id = data.get("category_id")
privacy = data["privacy"]
privacy_kinds = [kind.name for kind in PrivacyKinds]
if privacy not in privacy_kinds:
privacy = PrivacyKinds.Public.name
is_google_event = data.get("is_google_event", "True") == "True"
invited_emails = get_invited_emails(data["invited"])
uninvited_contacts = get_uninvited_regular_emails(
session,
owner_id,
title,
invited_emails,
)
shared_list = extract_shared_list_from_data(event_info=data, db=session)
latitude, longitude = None, None
if vc_link:
raise_if_zoom_link_invalid(vc_link)
else:
location_details = await get_location_coordinates(location)
if not isinstance(location_details, str):
location = location_details.name
latitude = location_details.latitude
longitude = location_details.longitude
event = create_event(
db=session,
title=title,
start=start,
end=end,
all_day=all_day,
owner_id=owner_id,
content=content,
location=location,
latitude=latitude,
longitude=longitude,
vc_link=vc_link,
invitees=invited_emails,
category_id=category_id,
availability=availability,
is_google_event=is_google_event,
shared_list=shared_list,
privacy=privacy,
)
if event_img:
image = process_image(event_img, event.id)
event.image = image
session.commit()
messages = get_messages(session, event, uninvited_contacts)
return RedirectResponse(
router.url_path_for("eventview", event_id=event.id)
+ f'?messages={"---".join(messages)}',
status_code=status.HTTP_302_FOUND,
)
def process_image(
img: bytes,
event_id: int,
img_height: int = IMAGE_HEIGHT,
) -> str:
"""Resized and saves picture without exif (to avoid malicious date))
according to required height and keep aspect ratio"""
try:
image = Image.open(io.BytesIO(img))
except IOError:
error_message = "The uploaded file is not a valid image"
logger.exception(error_message)
return
width, height = image.size
height_to_req_height = img_height / float(height)
new_width = int(float(width) * float(height_to_req_height))
resized = image.resize((new_width, img_height), Image.ANTIALIAS)
file_name = f"{event_id}{PICTURE_EXTENSION}"
image_data = list(resized.getdata())
image_without_exif = Image.new(resized.mode, resized.size)
image_without_exif.putdata(image_data)
image_without_exif.save(f"{UPLOAD_PATH}/{file_name}")
return file_name
def get_waze_link(event: Event) -> str:
"""Get a waze navigation link to the event location.
Returns:
If there are coordinates, waze will navigate to the exact location.
Otherwise, waze will look for the address that appears in the location.
If there is no address, an empty string will be returned."""
if not event.location:
return ""
# if event.latitude and event.longitude:
# coordinates = f"{event.latitude},{event.longitude}"
# return f"https://waze.com/ul?ll={coordinates}&navigate=yes"
url_location = urllib.parse.quote(event.location)
return f"https://waze.com/ul?q={url_location}&navigate=yes"
def raise_for_nonexisting_event(event_id: int) -> None:
error_message = f"Event ID does not exist. ID: {event_id}"
logger.exception(error_message)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=error_message,
)
@router.get("/{event_id}", include_in_schema=False)
async def eventview(
request: Request,
event_id: int,
db: Session = Depends(get_db),
) -> Response:
event, comments, end_format = get_event_data(db, event_id)
start_format = START_FORMAT
if event.all_day:
start_format = "%A, %d/%m/%Y"
end_format = ""
waze_link = get_waze_link(event)
event_considering_privacy = event_to_show(event, db)
if not event_considering_privacy:
raise_for_nonexisting_event(event.id)
messages = request.query_params.get("messages", "").split("---")
return templates.TemplateResponse(
"eventview.html",
{
"request": request,
"waze_link": waze_link,
"event": event_considering_privacy,
"comments": comments,
"start_format": start_format,
"end_format": end_format,
"messages": messages,
},
)
def check_event_owner(
event: Event,
session: Depends(get_db),
user: Optional[User] = None,
) -> bool:
# TODO use current_user after user system merge
if not user:
user = get_current_user(session)
is_owner = event.owner_id == user.id
return is_owner
def event_to_show(
event: Event,
session: Depends(get_db),
user: Optional[User] = None,
) -> Optional[Event]:
"""Check the given event's privacy and return
event/fixed private event/ nothing (hidden) accordingly"""
is_owner = check_event_owner(event, session, user)
if event.privacy == PrivacyKinds.Private.name and not is_owner:
event_dict = event.__dict__.copy()
if event_dict.get("_sa_instance_state", None):
event_dict.pop("_sa_instance_state")
event_dict.pop("id")
private_event = Event(**event_dict)
private_event.title = PrivacyKinds.Private.name
private_event.content = PrivacyKinds.Private.name
private_event.location = PrivacyKinds.Private.name
private_event.color = Null
private_event.invitees = PrivacyKinds.Private.name
private_event.category_id = Null
private_event.emotion = Null
return private_event
elif event.privacy == PrivacyKinds.Hidden.name and not is_owner:
return
elif event.privacy == PrivacyKinds.Public.name or is_owner:
return event
@router.post("/{event_id}/owner")
async def change_owner(
request: Request,
event_id: int,
db: Session = Depends(get_db),
):
form = await request.form()
if "username" not in form:
return RedirectResponse(
router.url_path_for("eventview", event_id=event_id),
status_code=status.HTTP_302_FOUND,
)
username = form["username"]
user = db.query(User).filter_by(username=username).first()
try:
user_id = user.id
except AttributeError as e:
error_message = f"Username does not exist. {form['username']}"
logger.exception(str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=error_message,
)
owner_to_update = {"owner_id": user_id}
_update_event(db, event_id, owner_to_update)
return RedirectResponse(
router.url_path_for("eventview", event_id=event_id),
status_code=status.HTTP_302_FOUND,
)
def by_id(db: Session, event_id: int) -> Event:
"""Get a single event by id"""
if not isinstance(db, Session):
error_message = (
f"Could not connect to database. "
f"db instance type received: {type(db)}"
)
logger.critical(error_message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=error_message,
)
try:
event = db.query(Event).filter_by(id=event_id).one()
except NoResultFound:
raise_for_nonexisting_event(event_id)
except MultipleResultsFound:
error_message = (
f"Multiple results found when getting event. Expected only one. "
f"ID: {event_id}"
)
logger.critical(error_message)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=error_message,
)
return event
def is_end_date_before_start_date(start_date: dt, end_date: dt) -> bool:
"""Check if the start date is earlier than the end date"""
return start_date > end_date
def check_change_dates_allowed(old_event: Event, event: Dict[str, Any]):
allowed = 1
try:
start_date = event.get("start", old_event.start)
end_date = event.get("end", old_event.end)
if is_end_date_before_start_date(start_date, end_date):
allowed = 0
except TypeError:
allowed = 0
if allowed == 0:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid times",
)
def is_fields_types_valid(to_check: Dict[str, Any], types: Dict[str, Any]):
"""validate dictionary values by dictionary of types"""
errors = []
for field_name, field_type in to_check.items():
if types[field_name] and not isinstance(field_type, types[field_name]):
errors.append(
f"{field_name} is '{type(field_type).__name__}' and"
+ f"it should be from type '{types[field_name].__name__}'",
)
logger.warning(errors)
if errors:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=errors,
)
def get_event_with_editable_fields_only(
event: Dict[str, Any],
) -> Dict[str, Any]:
"""Remove all keys that are not allowed to update"""
edit_event = {i: event[i] for i in UPDATE_EVENTS_FIELDS if i in event}
# Convert `availability` value into boolean.
if "availability" in edit_event.keys():
edit_event["availability"] = edit_event["availability"] == "True"
if "is_google_event" in edit_event.keys():
edit_event["is_google_event"] = edit_event["is_google_event"] == "True"
return edit_event
def _update_event(db: Session, event_id: int, event_to_update: Dict) -> Event:
try:
# Update database
db.query(Event).filter(Event.id == event_id).update(
event_to_update,
synchronize_session=False,
)
db.commit()
return by_id(db, event_id)
except (AttributeError, SQLAlchemyError) as e:
logger.exception(str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Internal server error",
)
def update_event(event_id: int, event: Dict, db: Session) -> Optional[Event]:
# TODO Check if the user is the owner of the event.
old_event = by_id(db, event_id)
event_to_update = get_event_with_editable_fields_only(event)
is_fields_types_valid(event_to_update, UPDATE_EVENTS_FIELDS)
check_change_dates_allowed(old_event, event_to_update)
if not event_to_update:
return None
event_updated = _update_event(db, event_id, event_to_update)
# TODO: Send emails to recipients.
return event_updated
def create_event(
db: Session,
title: str,
start,
end,
owner_id: int,
all_day: bool = False,
content: Optional[str] = None,
location: Optional[str] = None,
vc_link: str = None,
latitude: Optional[str] = None,
longitude: Optional[str] = None,
color: Optional[str] = None,
invitees: List[str] = None,
is_public: bool = False,
category_id: Optional[int] = None,
availability: bool = True,
is_google_event: bool = False,
shared_list: Optional[SharedList] = None,
privacy: str = PrivacyKinds.Public.name,
image: Optional[str] = None,
):
"""Creates an event and an association."""
invitees_concatenated = ",".join(invitees or [])
event = create_model(
db,
Event,
title=title,
start=start,
end=end,
privacy=privacy,
content=content,
owner_id=owner_id,
location=location,
latitude=latitude,
longitude=longitude,
vc_link=vc_link,
color=color,
emotion=get_emotion(title, content),
invitees=invitees_concatenated,
is_public=is_public,
all_day=all_day,
category_id=category_id,
shared_list=shared_list,
availability=availability,
is_google_event=is_google_event,
image=image,
)
create_model(db, UserEvent, user_id=owner_id, event_id=event.id)
return event
def sort_by_date(events: List[Event]) -> List[Event]:
"""Sorts the events by the start of the event."""
temp = events.copy()
return sorted(temp, key=attrgetter("start"))
def get_attendees_email(session: Session, event: Event):
return (
session.query(User.email)
.join(UserEvent)
.filter(UserEvent.events == event)
.all()
)
def get_participants_emails_by_event(db: Session, event_id: int) -> List[str]:
"""Returns a list of all the email address of the event invited users,
by event id."""
return [
email[0]
for email in db.query(User.email)
.select_from(Event)
.join(UserEvent, UserEvent.event_id == Event.id)
.join(User, User.id == UserEvent.user_id)
.filter(Event.id == event_id)
.all()
]
def _delete_event(db: Session, event: Event):
try:
# Delete event
db.delete(event)
# Delete user_event
db.query(UserEvent).filter(UserEvent.event_id == event.id).delete()
db.commit()
except (SQLAlchemyError, AttributeError) as e:
logger.exception(str(e))
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Deletion failed",
)
@router.delete("/{event_id}")
def delete_event(event_id: int, db: Session = Depends(get_db)) -> Response:
# TODO: Check if the user is the owner of the event.
event = by_id(db, event_id)
participants = get_participants_emails_by_event(db, event_id)
_delete_event(db, event)
if participants and event.start > dt.now():
pass
# TODO: Send them a cancellation notice
# if the deletion is successful
return RedirectResponse(url="/calendar", status_code=status.HTTP_200_OK)
def is_date_before(start_time: dt, end_time: dt) -> bool:
"""Check if the start_date is smaller then the end_time"""
try:
return start_time < end_time
except TypeError:
return False
def add_new_event(values: dict, db: Session) -> Optional[Event]:
"""Get User values and the DB Session insert the values
to the DB and refresh it exception in case that the keys
in the dict is not match to the fields in the DB
return the Event Class item"""
if not is_date_before(values["start"], values["end"]):
return None
try:
new_event = create_model(db, Event, **values)
create_model(
db,
UserEvent,
user_id=values["owner_id"],
event_id=new_event.id,
)
return new_event
except (AssertionError, AttributeError, TypeError) as e:
logger.exception(e)
return None
def add_user_to_event(session: Session, user_id: int, event_id: int):
user_already_connected = (
session.query(UserEvent)
.filter_by(event_id=event_id, user_id=user_id)
.all()
)
# if the user has a connection to the event,
# the function will recognize the duplicate and return false.
if user_already_connected:
return False
# if user is not registered to the event, the system will add him
association = UserEvent(user_id=user_id, event_id=event_id)
save(session, association)
return True
def extract_shared_list_from_data(
event_info: ImmutableMultiDict,
db: Session,
) -> Optional[SharedList]:
"""Extract shared list items from POST data.
Return:
SharedList: SharedList object stored in the database.
"""
raw_items = zip(
event_info.getlist("item-name"),
event_info.getlist("item-amount"),
event_info.getlist("item-participant"),
)
items = []
title = event_info.get("shared-list-title")
for name, amount, participant in raw_items:
item = SharedItem(name, amount, participant)
if _check_item_is_valid(item):
item_dict = item._asdict()
item_dict["amount"] = float(item_dict["amount"])
items.append(item_dict)
return _create_shared_list({title: items}, db)
def _check_item_is_valid(item: SharedItem) -> bool:
return (
item is not None
and item.amount.isnumeric()
and item.participant is not None
)
def _create_shared_list(
raw_shared_list: Dict[str, Dict[str, Any]],
db: Session,
) -> Optional[SharedList]:
try:
title = list(raw_shared_list.keys())[0] or "Shared List"
except IndexError as e:
logger.exception(e)
return None
shared_list = create_model(db, SharedList, title=title)
try:
items = list(raw_shared_list.values())[0]
for item in items:
item = create_model(db, SharedListItem, **item)
shared_list.items.append(item)
except (IndexError, KeyError) as e:
logger.exception(e)
return None
else:
return shared_list
def get_template_to_share_event(
event_id: int,
user_name: str,
db: Session,
request: Request,
) -> _TemplateResponse:
"""Gives shareable template of the event.
Args:
event_id: Event to share
user_name: The user who shares the event
db: The database to get the event from
request: The request we got from the user using FastAPI.
Returns:
Shareable HTML with data from the database about the event.
"""
event = by_id(db, event_id)
msg_info = {"sender_name": user_name, "event": event}
return templates.TemplateResponse(
"share_event.html",
{"request": request, "msg_info": msg_info},
)
@router.post("/{event_id}")
async def add_comment(
request: Request,
event_id: int,
session: Session = Depends(get_db),
) -> Response:
"""Creates a comment instance in the DB. Redirects back to the event's
comments tab upon creation."""
form = await request.form()
data = {
"user_id": get_current_user(session).id,
"event_id": event_id,
"content": form["comment"],
"time": dt.now(),
}
create_model(session, Comment, **data)
path = router.url_path_for("view_comments", event_id=str(event_id))
return RedirectResponse(path, status_code=status.HTTP_303_SEE_OTHER)
def get_event_data(db: Session, event_id: int) -> EVENT_DATA:
"""Retrieves all data necessary to display the event with the given id.
Args:
db (Session): DB session.
event_id (int): ID of Event to fetch data for.
Returns:
tuple(Event, list(dict(str: str)), str):
Tuple consisting of:
Event instance,
list of dictionaries with info for all comments in the event.
time format for the event's end time.
Raises:
None
"""
event = by_id(db, event_id)
comments = json.loads(cmt.display_comments(db, event))
end_format = (
"%H:%M" if event.start.date() == event.end.date() else START_FORMAT
)
return event, comments, end_format
@router.get("/{event_id}/comments")
async def view_comments(
request: Request,
event_id: int,
db: Session = Depends(get_db),
) -> Response:
"""Renders event comment tab view.
This essentially the same as `eventedit`, only with comments tab auto
showed."""
event, comments, end_format = get_event_data(db, event_id)
waze_link = get_waze_link(event)
return templates.TemplateResponse(
"eventview.html",
{
"request": request,
"event": event,
"waze_link": waze_link,
"comments": comments,
"comment": True,
"start_format": START_FORMAT,
"end_format": end_format,
},
)
@router.post("/comments/delete")
async def delete_comment(
request: Request,
db: Session = Depends(get_db),
) -> Response:
"""Deletes a comment instance from the db.
Redirects back to the event's comments tab upon deletion.
"""
form = await request.form()
try:
comment_id = int(form["comment_id"])
event_id = int(form["event_id"])
except ValueError:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid comment or event id",
)
cmt.delete_comment(db, comment_id)
path = router.url_path_for("view_comments", event_id=str(event_id))
return RedirectResponse(path, status_code=303)
@router.get("/timezone/country/{country_name}", include_in_schema=False)
async def check_timezone(
country_name,
request: Request,
db_session: Session = Depends(get_db),
) -> Response:
try:
country_timezone = (
db_session.query(Country.timezone)
.filter_by(name=country_name)
.first()[0]
)
except TypeError:
raise HTTPException(
status_code=404,
detail="The inserted country name is not found",
)
return {"timezone": country_timezone}