/usr/lib/python2.7/dist-packages/geopy/geocoders/geocodefarm.py is in python-geopy 1.3.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 | """
:class:`.GeocodeFarm` geocoder.
"""
from geopy.geocoders.base import Geocoder, DEFAULT_FORMAT_STRING, \
DEFAULT_TIMEOUT
from geopy.location import Location
from geopy.util import logger
from geopy.exc import GeocoderAuthenticationFailure, GeocoderQuotaExceeded, \
GeocoderServiceError
from geopy.compat import quote
__all__ = ("GeocodeFarm", )
class GeocodeFarm(Geocoder):
"""
Geocoder using the GeocodeFarm API. Documentation at:
https://www.geocodefarm.com/dashboard/documentation/
"""
def __init__(
self,
api_key,
format_string=DEFAULT_FORMAT_STRING,
timeout=DEFAULT_TIMEOUT,
proxies=None,
): # pylint: disable=R0913
"""
Create a geocoder for GeocodeFarm.
.. versionadded:: 0.99
:param string api_key: The API key required by GeocodeFarm to perform
geocoding requests.
:param string format_string: String containing '%s' where the
string to geocode should be interpolated before querying the
geocoder. For example: '%s, Mountain View, CA'. The default
is just '%s'.
:param dict proxies: If specified, routes this geocoder's requests
through the specified proxy. E.g., {"https": "192.0.2.0"}. For
more information, see documentation on
:class:`urllib2.ProxyHandler`.
Note that the GeocodeFarm geocoder does not support SSL.
"""
super(GeocodeFarm, self).__init__(
format_string, 'http', timeout, proxies
)
self.api_key = api_key
self.format_string = format_string
self.api = (
"%s://www.geocodefarm.com/api/forward/json/%s/" %
(self.scheme, self.api_key)
)
self.reverse_api = (
"%s://www.geocodefarm.com/api/reverse/json/%s/" %
(self.scheme, self.api_key)
)
def geocode(self, query, exactly_one=True, timeout=None):
"""
Geocode a location query.
:param string query: The address or query you wish to geocode.
:param bool exactly_one: Return one result or a list of results, if
available. GeocodeFarm's API will always return at most one
result.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
"""
url = "".join((
self.api,
quote((self.format_string % query).encode('utf8'))
))
logger.debug("%s.geocode: %s", self.__class__.__name__, url)
return self._parse_json(
self._call_geocoder(url, timeout=timeout), exactly_one
)
def reverse(self, query, exactly_one=True, timeout=None):
"""
Returns a reverse geocoded location.
:param query: The coordinates for which you wish to obtain the
closest human-readable addresses.
:type query: :class:`geopy.point.Point`, list or tuple of (latitude,
longitude), or string as "%(latitude)s, %(longitude)s"
:param bool exactly_one: Return one result or a list of results, if
available. GeocodeFarm's API will always return at most one
result.
:param int timeout: Time, in seconds, to wait for the geocoding service
to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
exception. Set this only if you wish to override, on this call
only, the value set during the geocoder's initialization.
"""
lat, lon = self._coerce_point_to_string(query).split(',')
url = "".join((
self.reverse_api,
quote(("%s/%s" % (lat, lon)).encode('utf8'))
))
logger.debug("%s.reverse: %s", self.__class__.__name__, url)
return self._parse_json(
self._call_geocoder(url, timeout=timeout), exactly_one
)
@staticmethod
def parse_code(place):
"""
Parse each resource.
"""
coordinates = place.get('COORDINATES', {})
address = place.get('ADDRESS', {})
latitude = coordinates.get('latitude', None)
longitude = coordinates.get('longitude', None)
placename = address.get('address_returned', None)
if placename is None:
placename = address.get('address', None)
if latitude and longitude:
latitude = float(latitude)
longitude = float(longitude)
return Location(placename, (latitude, longitude), place)
def _parse_json(self, api_result, exactly_one):
if api_result is None:
return None
geocoding_results = api_result["geocoding_results"]
self._check_for_api_errors(geocoding_results)
place = self.parse_code(geocoding_results)
if exactly_one is True:
return place
else:
return [place] # GeocodeFarm always only returns one result
@staticmethod
def _check_for_api_errors(geocoding_results):
"""
Raise any exceptions if there were problems reported
in the api response.
"""
status_result = geocoding_results.get("STATUS", {})
api_call_success = status_result.get("status", "") == "SUCCESS"
if not api_call_success:
access_error = status_result.get("access")
access_error_to_exception = {
'API_KEY_INVALID': GeocoderAuthenticationFailure,
'OVER_QUERY_LIMIT': GeocoderQuotaExceeded,
}
exception_cls = access_error_to_exception.get(
access_error, GeocoderServiceError
)
raise exception_cls(access_error)
|