forked from balrog-kun/osm-addr-tools
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathoverpass.py
70 lines (57 loc) · 1.97 KB
/
overpass.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
import io
from urllib.parse import urlencode
import logging
import math
import requests
import tqdm
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
__log = logging.getLogger(__name__)
def requests_retry_session(
retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None
):
session = session or requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
__overpassurl = "http://overpass.osm.rambler.ru/cgi/interpreter"
__overpassurl = "http://overpass-api.de/api/interpreter"
__overpassurl = "http://api.openstreetmap.fr/oapi/interpreter/"
__overpassurl = "http://osm-cdn.vink.pl/api/interpreter"
def get_url_for_query(qry: str):
return (
__overpassurl
+ "?"
+ urlencode({"data": qry.replace("\t", "").replace("\n", "")})
)
def query(qry, desc="") -> bytes:
# TODO - check if the query succeeded
__log.debug("Query %s , server: %s", qry, __overpassurl)
r = requests_retry_session().get(get_url_for_query(qry), timeout=180, stream=True)
total_size = int(r.headers.get("content-length", 0))
block_size = 128 * 1024
wrote = 0
raw_data = bytearray()
if desc:
desc = "(" + desc + ")"
with tqdm.tqdm(
total=math.ceil(total_size // block_size),
unit="B",
unit_scale=True,
desc="Downloading from Overpass{}".format(desc),
) as progressbar:
for data in r.iter_content(block_size):
wrote += len(data)
progressbar.update(len(data))
raw_data += data
if total_size != 0 and wrote != total_size:
raise RuntimeError("Expected %d but got %d bytes".format(total_size, wrote))
return raw_data