-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.py
More file actions
98 lines (73 loc) · 2.44 KB
/
init.py
File metadata and controls
98 lines (73 loc) · 2.44 KB
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
import logging
import os
import pathlib
import typing
from contextlib import asynccontextmanager
import requests
from fastapi import FastAPI
from config import settings
from geocoding import FastGeocoder
class SharedMem(typing.TypedDict):
geocoder: FastGeocoder | None
super_simplified_geocoder: FastGeocoder | None
shared_mem: SharedMem = {"geocoder": None, "super_simplified_geocoder": None}
logger = logging.getLogger(__name__)
def _download_file(
*,
url: str,
dest: str,
timeout: int = 60,
chunk_size: int = 128,
):
response = requests.get(url=url, stream=True, timeout=timeout)
response.raise_for_status()
with open(dest, "wb") as file:
for chunk in response.iter_content(chunk_size=chunk_size):
file.write(chunk)
def _download_geodata(
*,
name: str,
file_path: str,
url_path: str,
):
dir_path = pathlib.Path(os.path.dirname(file_path))
dir_path.mkdir(parents=True, exist_ok=True)
if not os.path.exists(file_path):
logger.info(f"Downloading resources for {name}.")
_download_file(url=url_path, dest=file_path)
logger.info(f"Download complete for {name} and stored at {file_path}.")
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("The service is starting.")
_download_geodata(
name="WAB",
url_path=settings.WAB_DOWNLOAD_URL,
file_path=settings.WAB_FILE_PATH,
)
_download_geodata(
name="GAUL",
url_path=settings.GAUL_DOWNLOAD_URL,
file_path=settings.GAUL_FILE_PATH,
)
_download_geodata(
name="SUPER_SIMPLIFIED_WAB",
url_path=settings.SUPER_SIMPLIFIED_WAB_DOWNLOAD_URL,
file_path=settings.SUPER_SIMPLIFIED_WAB_FILE_PATH,
)
_download_geodata(
name="SUPER_SIMPLIFIED_GAUL",
url_path=settings.SUPER_SIMPLIFIED_GAUL_DOWNLOAD_URL,
file_path=settings.SUPER_SIMPLIFIED_GAUL_FILE_PATH,
)
logger.info("Initializing geocoder")
geocoder = FastGeocoder(
settings.WAB_FILE_PATH,
settings.GAUL_FILE_PATH,
)
super_simplified_geocoder = FastGeocoder(settings.SUPER_SIMPLIFIED_WAB_FILE_PATH, settings.SUPER_SIMPLIFIED_GAUL_FILE_PATH)
shared_mem["geocoder"] = geocoder
shared_mem["super_simplified_geocoder"] = super_simplified_geocoder
logger.info("Initialization for geocoder complete.")
yield
logger.info("The service is shutting down.")
__all__ = ["lifespan", "shared_mem"]