Blame view

flaskr/geocoder.py 1.02 KB
d8886db8   Goutte   Add a cached geoc...
1
import shelve
3b3b818e   Antoine Goutenoir   fix: more TLS she...
2
import ssl
d8886db8   Goutte   Add a cached geoc...
3
4
import time

3b3b818e   Antoine Goutenoir   fix: more TLS she...
5
import certifi
5e63d13d   Antoine Goutenoir   fix: use HTTP, no...
6
import geopy
3b3b818e   Antoine Goutenoir   fix: more TLS she...
7
import geopy.geocoders
5e63d13d   Antoine Goutenoir   fix: use HTTP, no...
8

2b4cf2a1   Antoine Goutenoir   fix: use a qualif...
9
from flaskr.core import get_path
e42b2aa7   Antoine Goutenoir   Use path relativi...
10

3b3b818e   Antoine Goutenoir   fix: more TLS she...
11
12
13
ctx = ssl.create_default_context(cafile=certifi.where())
geopy.geocoders.options.default_ssl_context = ctx

d8886db8   Goutte   Add a cached geoc...
14
15

class CachedGeocoder:
e6e3ec38   Antoine Goutenoir   There must be a P...
16

d8886db8   Goutte   Add a cached geoc...
17
    def __init__(self, source="Nominatim", geocache="geocache.db"):
5e63d13d   Antoine Goutenoir   fix: use HTTP, no...
18
        self.geocoder = getattr(geopy.geocoders, source)(scheme='http')
e42b2aa7   Antoine Goutenoir   Use path relativi...
19
        self.cache = shelve.open(get_path(geocache), writeback=True)
9b550055   Antoine Goutenoir   Clean up.
20
        # self.timestamp = time.time() + 1.5
d8886db8   Goutte   Add a cached geoc...
21
22
23

    def geocode(self, address):
        if address not in self.cache:
e42b2aa7   Antoine Goutenoir   Use path relativi...
24
25
            # time.sleep(max(0, 1 - (time.time() - self.timestamp)))
            time.sleep(1.618)
9b550055   Antoine Goutenoir   Clean up.
26
            # self.timestamp = time.time()
70aa301f   Antoine Goutenoir   Implement another...
27
28
29
30
31
32
            self.cache[address] = self.geocoder.geocode(
                query=address,
                timeout=5,
                language='en_US',  # urgh
                addressdetails=True,  # only works with Nominatim /!.
            )
d8886db8   Goutte   Add a cached geoc...
33
        return self.cache[address]
52d49719   Antoine Goutenoir   Improve the geoco...
34
35
36

    def close(self):
        self.cache.close()