Blame view

flaskr/geocoder.py 797 Bytes
d8886db8   Goutte   Add a cached geoc...
1
2
3
4
5
6
import geopy
import shelve
import time


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

d8886db8   Goutte   Add a cached geoc...
8
9
10
11
12
13
14
15
16
    def __init__(self, source="Nominatim", geocache="geocache.db"):
        self.geocoder = getattr(geopy.geocoders, source)()
        self.cache = shelve.open(geocache, writeback=True)
        self.timestamp = time.time() + 1.5

    def geocode(self, address):
        if address not in self.cache:
            time.sleep(max(0, 1 - (time.time() - self.timestamp)))
            self.timestamp = time.time()
70aa301f   Antoine Goutenoir   Implement another...
17
18
19
20
21
22
            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...
23
        return self.cache[address]
52d49719   Antoine Goutenoir   Improve the geoco...
24
25
26

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