|
| 1 | +import functools |
1 | 2 | import logging
|
2 | 3 | import re
|
3 | 4 | from typing import List, NamedTuple, Set, Union
|
|
11 | 12 | from sqlalchemy.orm import Session
|
12 | 13 | from starlette.status import HTTP_400_BAD_REQUEST
|
13 | 14 |
|
14 |
| -from app.database.models import Event |
| 15 | +from app.database.models import Country, Event |
| 16 | +from app.resources.countries import countries |
15 | 17 |
|
16 | 18 | ZOOM_REGEX = re.compile(r"https://.*?\.zoom.us/[a-z]/.[^.,\b\s]+")
|
17 | 19 |
|
@@ -114,6 +116,43 @@ def get_messages(
|
114 | 116 | return messages
|
115 | 117 |
|
116 | 118 |
|
| 119 | +def add_countries_to_db(session: Session) -> None: |
| 120 | + """ |
| 121 | + Adding all new countries to the "Country" table in the database. |
| 122 | + Information is based on the "countries" list. |
| 123 | + (The list is located in app/resources/countries.py) |
| 124 | + Names are described either as: |
| 125 | + "Country Name, City Name" or |
| 126 | + "Country Name" solely. |
| 127 | + Timezones are described as "Continent/ City Name" |
| 128 | + for example: |
| 129 | + name: Israel, Jerusalem |
| 130 | + timezone: Asia/Jerusalem |
| 131 | + """ |
| 132 | + for country in countries: |
| 133 | + partial_name = country["name"] |
| 134 | + for capital_city in country["timezones"]: |
| 135 | + capital_city_name = capital_city.split("/")[-1] |
| 136 | + if partial_name != capital_city_name: |
| 137 | + name = partial_name + ", " + capital_city_name |
| 138 | + else: |
| 139 | + name = capital_city_name |
| 140 | + new_country = Country(name=name, timezone=str(capital_city)) |
| 141 | + session.merge(new_country) |
| 142 | + session.commit() |
| 143 | + |
| 144 | + |
| 145 | +@functools.lru_cache |
| 146 | +def get_all_countries_names(session: Session) -> List[str]: |
| 147 | + """ |
| 148 | + Returns a cached list of the countries names. |
| 149 | + """ |
| 150 | + db_entity = session.query(Country).first() |
| 151 | + if not db_entity: |
| 152 | + add_countries_to_db(session=session) |
| 153 | + return session.query(Country.name).all() |
| 154 | + |
| 155 | + |
117 | 156 | async def get_location_coordinates(
|
118 | 157 | address: str,
|
119 | 158 | ) -> Union[Location, str]:
|
|
0 commit comments