/usr/lib/python3/dist-packages/geopy/geocoders/base.py is in python3-geopy 1.11.0+ds1-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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | """
:class:`.GeoCoder` base object from which other geocoders are templated.
"""
from ssl import SSLError
from socket import timeout as SocketTimeout
import json
from geopy.compat import (
string_compare,
HTTPError,
py3k,
urlopen as urllib_urlopen,
build_opener,
ProxyHandler,
URLError,
install_opener,
Request,
)
from geopy.point import Point
from geopy.exc import (
GeocoderServiceError,
ConfigurationError,
GeocoderTimedOut,
GeocoderAuthenticationFailure,
GeocoderQuotaExceeded,
GeocoderQueryError,
GeocoderInsufficientPrivileges,
GeocoderUnavailable,
GeocoderParseError,
)
from geopy.util import decode_page, __version__
__all__ = (
"Geocoder",
"DEFAULT_FORMAT_STRING",
"DEFAULT_SCHEME",
"DEFAULT_TIMEOUT",
"DEFAULT_WKID",
)
DEFAULT_FORMAT_STRING = '%s'
DEFAULT_SCHEME = 'https'
DEFAULT_TIMEOUT = 1
DEFAULT_WKID = 4326
DEFAULT_USER_AGENT = "geopy/%s" % __version__
ERROR_CODE_MAP = {
400: GeocoderQueryError,
401: GeocoderAuthenticationFailure,
402: GeocoderQuotaExceeded,
403: GeocoderInsufficientPrivileges,
407: GeocoderAuthenticationFailure,
412: GeocoderQueryError,
413: GeocoderQueryError,
414: GeocoderQueryError,
502: GeocoderServiceError,
503: GeocoderTimedOut,
504: GeocoderTimedOut
}
class Geocoder(object): # pylint: disable=R0921
"""
Template object for geocoders.
"""
def __init__(
self,
format_string=DEFAULT_FORMAT_STRING,
scheme=DEFAULT_SCHEME,
timeout=DEFAULT_TIMEOUT,
proxies=None,
user_agent=None
):
"""
Mostly-common geocoder validation, proxies, &c. Not all geocoders
specify format_string and such.
"""
self.format_string = format_string
self.scheme = scheme
if self.scheme not in ('http', 'https'): # pragma: no cover
raise ConfigurationError(
'Supported schemes are `http` and `https`.'
)
self.proxies = proxies
self.timeout = timeout
self.headers = {'User-Agent': user_agent or DEFAULT_USER_AGENT}
if self.proxies:
install_opener(
build_opener(
ProxyHandler(self.proxies)
)
)
self.urlopen = urllib_urlopen
@staticmethod
def _coerce_point_to_string(point):
"""
Do the right thing on "point" input. For geocoders with reverse
methods.
"""
if isinstance(point, Point):
return ",".join((str(point.latitude), str(point.longitude)))
elif isinstance(point, (list, tuple)):
return ",".join((str(point[0]), str(point[1]))) # -altitude
elif isinstance(point, string_compare):
return point
else: # pragma: no cover
raise ValueError("Invalid point")
def _parse_json(self, page, exactly_one): # pragma: no cover
"""
Template for subclasses
"""
raise NotImplementedError()
def _call_geocoder(
self,
url,
timeout=None,
raw=False,
requester=None,
deserializer=json.loads,
**kwargs
):
"""
For a generated query URL, get the results.
"""
requester = requester or self.urlopen
if not requester:
req = Request(url=url, headers=self.headers)
else:
# work around for placefinder's use of requests
req = url
try:
page = requester(req, timeout=(timeout or self.timeout), **kwargs)
except Exception as error: # pylint: disable=W0703
message = (
str(error) if not py3k
else (
str(error.args[0])
if len(error.args)
else str(error)
)
)
if hasattr(self, '_geocoder_exception_handler'):
self._geocoder_exception_handler(error, message) # pylint: disable=E1101
if isinstance(error, HTTPError):
code = error.getcode()
try:
raise ERROR_CODE_MAP[code](message)
except KeyError:
raise GeocoderServiceError(message)
elif isinstance(error, URLError):
if "timed out" in message:
raise GeocoderTimedOut('Service timed out')
elif "unreachable" in message:
raise GeocoderUnavailable('Service not available')
elif isinstance(error, SocketTimeout):
raise GeocoderTimedOut('Service timed out')
elif isinstance(error, SSLError):
if "timed out" in message:
raise GeocoderTimedOut('Service timed out')
raise GeocoderServiceError(message)
if hasattr(page, 'getcode'):
status_code = page.getcode()
elif hasattr(page, 'status_code'):
status_code = page.status_code
else:
status_code = None
if status_code in ERROR_CODE_MAP:
raise ERROR_CODE_MAP[page.status_code]("\n%s" % decode_page(page))
if raw:
return page
page = decode_page(page)
if deserializer is not None:
try:
return deserializer(page)
except ValueError:
raise GeocoderParseError(
"Could not deserialize using deserializer:\n%s" % page
)
else:
return page
def geocode(self, query, exactly_one=True, timeout=None):
"""
Implemented in subclasses.
"""
raise NotImplementedError()
def reverse(self, query, exactly_one=True, timeout=None):
"""
Implemented in subclasses.
"""
raise NotImplementedError()
|