Blame view

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

e42b2aa7   Antoine Goutenoir   Use path relativi...
5
6
from core import get_path

d8886db8   Goutte   Add a cached geoc...
7
8

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

d8886db8   Goutte   Add a cached geoc...
10
11
    def __init__(self, source="Nominatim", geocache="geocache.db"):
        self.geocoder = getattr(geopy.geocoders, source)()
e42b2aa7   Antoine Goutenoir   Use path relativi...
12
        self.cache = shelve.open(get_path(geocache), writeback=True)
9b550055   Antoine Goutenoir   Clean up.
13
        # self.timestamp = time.time() + 1.5
d8886db8   Goutte   Add a cached geoc...
14
15
16

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

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