-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend.py
More file actions
32 lines (27 loc) · 898 Bytes
/
Copy pathbackend.py
File metadata and controls
32 lines (27 loc) · 898 Bytes
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
import time
import urllib
from .config import NOMINATIM_URL, API_RATE_LIMIT, USER_AGENT
LAST_REQUEST_TIME = time.time()
def query_osm_boundary(name: str):
global LAST_REQUEST_TIME
params={
"q": name,
"format": "json",
"addressdetails": 1,
"limit": 10,
"polygon_geojson": 0,
}
url = f"{NOMINATIM_URL}?{urllib.parse.urlencode(params)}"
now = time.time()
wait = API_RATE_LIMIT - (now - LAST_REQUEST_TIME)
if wait > 0:
time.sleep(wait)
LAST_REQUEST_TIME = time.time()
try:
req = urllib.request.Request(url, headers={
"User-Agent": USER_AGENT, "Accept": "application/json",
})
with urllib.request.urlopen(req, timeout=30) as resp:
return resp.read().decode("utf-8")
except Exception as exc:
raise RuntimeError(f"Nominatim request failed: {exc}") from exc