-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservice.py
72 lines (51 loc) · 1.93 KB
/
service.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
import logging
from contextlib import asynccontextmanager
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
from fastapi import FastAPI
from download import check_and_download_gaul_file
from geocoding import GAULGeocoder
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
logger.setLevel(logging.INFO)
scheduler = BackgroundScheduler()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Life span handler"""
# Run every first day of the month (midnight)
scheduler.add_job(scheduled_task, CronTrigger(day="1", hour="0", minute="0"))
scheduler.start()
yield
logger.info("The service is shutting down.")
app = FastAPI(lifespan=lifespan)
file_path = check_and_download_gaul_file()
if not file_path:
raise FileNotFoundError("Geocoding source file couldn't be made available.")
geocoder = GAULGeocoder(gpkg_path=file_path)
def scheduled_task():
"""Scheduled Task"""
global file_path, geocoder
file_path = check_and_download_gaul_file(scheduler_trigger=True)
if not file_path:
raise FileNotFoundError("Geocoding source file couldn't be made available.")
geocoder = GAULGeocoder(gpkg_path=file_path)
@app.get("/")
async def home():
"""Test url"""
return {"message": "Welcome to geocoding as service"}
@app.get("/by_admin_units")
async def get_by_admin_units(admin_units: str):
"""Get the geometry based on admin units"""
if not geocoder:
logger.error("Geocoder is not set.")
return {}
result = geocoder.get_geometry_from_admin_units(admin_units)
return result or {}
@app.get("/by_country_name")
async def get_by_country_name(country_name: str):
"""Get the geometry based on country name"""
if not geocoder:
logger.error("Geocoder is not set.")
return {}
result = geocoder.get_geometry_by_country_name(country_name)
return result or {}