Example #1
0
    def __init__(
        self,
        format_string=None,
        scheme=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        ssl_context=DEFAULT_SENTINEL,
    ):
        """
        Mostly-common geocoder validation, proxies, &c. Not all geocoders
        specify format_string and such.
        """
        self.format_string = format_string or options.default_format_string
        self.scheme = scheme or options.default_scheme
        if self.scheme not in ('http', 'https'):
            raise ConfigurationError(
                'Supported schemes are `http` and `https`.')
        self.timeout = (timeout if timeout is not DEFAULT_SENTINEL else
                        options.default_timeout)
        self.proxies = (proxies if proxies is not DEFAULT_SENTINEL else
                        options.default_proxies)
        self.headers = {'User-Agent': user_agent or options.default_user_agent}
        self.ssl_context = (ssl_context if ssl_context is not DEFAULT_SENTINEL
                            else options.default_ssl_context)

        if self.proxies:
            opener = build_opener_with_context(
                self.ssl_context,
                ProxyHandler(self.proxies),
            )
        else:
            opener = build_opener_with_context(self.ssl_context, )
        self.urlopen = opener.open
Example #2
0
    def __init__(self,
                 format_string=DEFAULT_FORMAT_STRING,
                 scheme=DEFAULT_SCHEME,
                 timeout=DEFAULT_TIMEOUT,
                 proxies=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

        # Add urllib proxy support using environment variables or
        # built in OS proxy details
        # See: http://docs.python.org/2/library/urllib2.html
        # And: http://stackoverflow.com/questions/1450132/proxy-with-urllib2
        if self.proxies is None:
            self.urlopen = urllib_urlopen
        else:
            self.urlopen = build_opener(ProxyHandler(self.proxies))
Example #3
0
    def __init__(self,
                 country_bias=None,
                 username=None,
                 timeout=DEFAULT_TIMEOUT,
                 proxies=None):
        """
        :param string country_bias:

        :param string username:

        :param int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
            exception.

            .. versionadded:: 0.97

        :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`.

            .. versionadded:: 0.96
        """
        super(GeoNames, self).__init__(scheme='http',
                                       timeout=timeout,
                                       proxies=proxies)
        if username == None:
            raise ConfigurationError(
                'No username given, required for api access.  If you do not '
                'have a GeoNames username, sign up here: '
                'http://www.geonames.org/login')
        self.username = username
        self.country_bias = country_bias
        self.api = "%s://api.geonames.org/searchJSON" % self.scheme
Example #4
0
    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:
            opener = build_opener(
                ProxyHandler(self.proxies)
            )
            self.urlopen = opener.open
        else:
            self.urlopen = urllib_urlopen
Example #5
0
    def __init__(self,
                 token=None,
                 api_version=2,
                 timeout=DEFAULT_TIMEOUT,
                 proxies=None,
                 user_agent=None):
        """
        Create a TomTom-based geocoder.

        :param int token: The token for you authentication.

        :param string scheme: Desired scheme. If authenticated mode is in use,
            it must be 'https'.

        :param int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
            exception.

        :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`.
        """
        super(TomTom, self).__init__(scheme=DEFAULT_SCHEME,
                                     timeout=timeout,
                                     proxies=proxies,
                                     user_agent=user_agent)

        if not token:
            raise ConfigurationError("The token must be specified.")

        self.token = token

        self.api = '%s://api.tomtom.com/search/%s/' % (self.scheme,
                                                       api_version)
Example #6
0
    def __init__(
            self,
            auth_id,
            auth_token,
            candidates=1,
            scheme=DEFAULT_SCHEME,
            timeout=DEFAULT_TIMEOUT,
            proxies=None,
            user_agent=None,
        ):  # pylint: disable=R0913
        """
        Initialize a customized SmartyStreets LiveAddress geocoder.

        :param string auth_id: Valid `Auth ID` from SmartyStreets.

            .. versionadded:: 1.5.0

        :param string auth_token: Valid `Auth Token` from SmartyStreets.

        :param int candidates: An integer between 1 and 10 indicating the max
            number of candidate addresses to return if a valid address
            could be found.

        :param string scheme: Use 'https' or 'http' as the API URL's scheme.
            Default is https. Note that SSL connections' certificates are not
            verified.

            .. versionadded:: 0.97

            .. versionchanged:: 1.8.0
            LiveAddress now requires `https`. Specifying `scheme=http` will
            result in a :class:`geopy.exc.ConfigurationError`.

        :param int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising an :class:`geopy.exc.GeocoderTimedOut`
            exception.

            .. versionadded:: 0.97

        :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`.

            .. versionadded:: 0.96
        """
        super(LiveAddress, self).__init__(
            timeout=timeout, proxies=proxies, user_agent=user_agent
        )
        if scheme == "http":
            raise ConfigurationError("LiveAddress now requires `https`.")
        self.scheme = scheme
        self.auth_id = auth_id
        self.auth_token = auth_token
        if candidates:
            if not 1 <= candidates <= 10:
                raise ValueError('candidates must be between 1 and 10')
        self.candidates = candidates
        self.api = '%s://api.smartystreets.com/street-address' % self.scheme
Example #7
0
    def geocode(self, query='', street='', city='', state='', zip_cd='',
                n_matches=1, timeout=60):
        """
        Return a ranked list of locations for an address.
        :param string query: The single-line address you wish to geocode.
        :param string street: Optional, Street if not using single-line
        :param string city: Optional, City
        :param string state: Optional, State
        :param string zip_cd: Optional, Zip Code
        :param int n_matches: Return top n matches.
        :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.
        """

        params = {'Single Line Input': query,
                  'Street': street,
                  'City': city,
                  'State': state,
                  'ZIP': zip_cd,
                  'f': 'json',
                  'maxLocations': n_matches}

        if not (len(query) or len(street)):
            raise ConfigurationError(
                "Street or Full Address must be entered."
            )

        url = "?".join((self.api, urlencode(params)))

        logger.debug("%s.geocode: %s", self.__class__.__name__, url)
        response = self._call_geocoder(url, timeout=timeout)

        # Handle any errors; recursing in the case of an expired token
        if 'error' in response:
            if response['error']['code'] == self._TOKEN_EXPIRED:
                self.retry += 1
                self._refresh_authentication_token()
                return self.geocode(query, street, city, state, zip_cd, n_matches, timeout)
            raise GeocoderServiceError(str(response['error']))

        if not len(response['candidates']):
            return None

        geocoded = []
        candidate_cnt = 1
        for candidate in response['candidates']:
            geocoded.append({
                'candidate':candidate_cnt,
                'attributes':{
                    'score':candidate['score'],
                    'match_addr':candidate['address'],
                    'location':{'x':candidate['location']['x'],
                                'y':candidate['location']['y']}}})
            candidate_cnt += 1

        return {'candidates':geocoded}
Example #8
0
    def __init__(
        self,
        country_bias=None,
        username=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        format_string=None,
        ssl_context=DEFAULT_SENTINEL,
    ):
        """
        :param str country_bias:

        :param str username: GeoNames username, required. Sign up here:
            http://www.geonames.org/login

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

            .. versionadded:: 1.14.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0
        """
        super(GeoNames, self).__init__(
            format_string=format_string,
            scheme='http',
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if username is None:
            raise ConfigurationError(
                'No username given, required for api access.  If you do not '
                'have a GeoNames username, sign up here: '
                'http://www.geonames.org/login')
        self.username = username
        self.country_bias = country_bias
        domain = 'api.geonames.org'
        self.api = ("%s://%s%s" % (self.scheme, domain, self.geocode_path))
        self.api_reverse = ("%s://%s%s" %
                            (self.scheme, domain, self.reverse_path))
Example #9
0
    def __init__(
        self,
        api_key=None,
        format_string=DEFAULT_FORMAT_STRING,
        scheme=DEFAULT_SCHEME,
        timeout=DEFAULT_TIMEOUT,
        proxies=None,
        user_agent=None,
    ):  # pylint: disable=R0913
        """
        Initialize an Open MapQuest geocoder with location-specific
        address information.

        :param string api_key: API key provided by MapQuest.

            .. versionchanged:: 1.12.0
               OpenMapQuest now requires an API key. Using an empty key will
               result in a :class:`geopy.exc.ConfigurationError`.

        :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 string scheme: Use 'https' or 'http' as the API URL's scheme.
            Default is https. Note that SSL connections' certificates are not
            verified.

            .. versionadded:: 0.97

        :param int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
            exception.

            .. versionadded:: 0.97

        :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`.

            .. versionadded:: 0.96

        :param string user_agent: Use a custom User-Agent header.

            .. versionadded:: 1.12.0
        """
        super(OpenMapQuest, self).__init__(format_string,
                                           scheme,
                                           timeout,
                                           proxies,
                                           user_agent=user_agent)
        if not api_key:
            raise ConfigurationError('OpenMapQuest requires an API key')
        self.api_key = api_key
        self.api = "%s://open.mapquestapi.com/nominatim/v1/search" \
                    "?format=json" % self.scheme
Example #10
0
    def __init__(
        self,
        api_key=None,
        format_string=None,
        scheme=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        ssl_context=DEFAULT_SENTINEL,
    ):
        """

        :param str api_key: API key provided by MapQuest, required.

            .. versionchanged:: 1.12.0
               OpenMapQuest now requires an API key. Using an empty key will
               result in a :class:`geopy.exc.ConfigurationError`.

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0
        """
        super(OpenMapQuest, self).__init__(
            format_string=format_string,
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if not api_key:
            raise ConfigurationError('OpenMapQuest requires an API key')
        self.api_key = api_key
        self.api = ("%s://open.mapquestapi.com/nominatim/v1/search"
                    "?format=json" % self.scheme)
Example #11
0
 def __init__(self,
              username=None,
              password=None,
              format_string=None,
              proxies=None):
     super(GeocoderDotUS, self).__init__(format_string, proxies)
     if username and password is None:
         raise ConfigurationError(
             "password must be specified with username")
     self.username = username
     self.__password = password
Example #12
0
 def __init__(self, country_bias=None, username=None, proxies=None):
     super(GeoNames, self).__init__(proxies=proxies)
     if username == None:
         raise ConfigurationError(
             'No username given, required for api access.  If you do not '
             'have a GeoNames username, sign up here: '
             'http://www.geonames.org/login'
         )
     self.username = username
     self.country_bias = country_bias
     self.api = "http://api.geonames.org/searchJSON"
Example #13
0
    def __init__(self, domain='maps.googleapis.com', protocol='http', # pylint: disable=R0913
                 client_id=None, secret_key=None, proxies=None):
        """
        Initialize a customized Google geocoder.

        API authentication is only required for Google Maps Premier customers.

        :param string domain: Should be the localized Google Maps domain to
            connect to. The default is 'maps.google.com', but if you're
            geocoding address in the UK (for example), you may want to set it
            to 'maps.google.co.uk' to properly bias results.

        :param string protocol: http or https.

        :param string client_id: If using premier, the account client id.

        :param string secret_key: If using premier, the account secret key.
        """
        super(GoogleV3, self).__init__(proxies=proxies)

        if protocol not in ('http', 'https'):
            raise ConfigurationError('Supported protocols are http and https.')
        if client_id and not secret_key:
            raise ConfigurationError('Must provide secret_key with client_id.')
        if secret_key and not client_id:
            raise ConfigurationError('Must provide client_id with secret_key.')

        self.domain = domain.strip('/')
        self.protocol = protocol
        self.doc = {}

        if client_id and secret_key:
            self.premier = True
            self.client_id = client_id
            self.secret_key = secret_key
        else:
            self.premier = False
            self.client_id = None
            self.secret_key = None
Example #14
0
    def __init__(
            self,
            username=None,
            password=None,
            format_string=DEFAULT_FORMAT_STRING,
            timeout=DEFAULT_TIMEOUT,
            proxies=None,
            user_agent=None,
        ):  # pylint: disable=R0913
        """
        :param string username:

        :param string password:

        :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 int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising an :class:`geopy.exc.GeocoderTimedOut`
            exception.

            .. versionadded:: 0.97

        :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`.

            .. versionadded:: 0.96

        :param string user_agent: Use a custom User-Agent header.

            .. versionadded:: 1.12.0
        """
        super(GeocoderDotUS, self).__init__(
            format_string=format_string, timeout=timeout, proxies=proxies, user_agent=user_agent
        )
        if username or password:
            if not (username and password):
                raise ConfigurationError(
                    "Username and password must both specified"
                )
            self.authenticated = True
            self.api = "http://geocoder.us/member/service/namedcsv"
        else:
            self.authenticated = False
            self.api = "http://geocoder.us/service/namedcsv"
        self.username = username
        self.password = password
Example #15
0
    def __init__(self,
                 *,
                 scheme=None,
                 timeout=DEFAULT_SENTINEL,
                 proxies=DEFAULT_SENTINEL,
                 user_agent=None,
                 ssl_context=DEFAULT_SENTINEL,
                 adapter_factory=None):
        self.scheme = scheme or options.default_scheme
        if self.scheme not in ('http', 'https'):
            raise ConfigurationError(
                'Supported schemes are `http` and `https`.')
        self.timeout = (timeout if timeout is not DEFAULT_SENTINEL else
                        options.default_timeout)
        self.proxies = (proxies if proxies is not DEFAULT_SENTINEL else
                        options.default_proxies)
        self.headers = {'User-Agent': user_agent or options.default_user_agent}
        self.ssl_context = (ssl_context if ssl_context is not DEFAULT_SENTINEL
                            else options.default_ssl_context)

        if isinstance(self.proxies, str):
            self.proxies = {'http': self.proxies, 'https': self.proxies}

        if adapter_factory is None:
            adapter_factory = options.default_adapter_factory
        self.adapter = adapter_factory(
            proxies=self.proxies,
            ssl_context=self.ssl_context,
        )
        if isinstance(self.adapter, BaseSyncAdapter):
            self.__run_async = False
        elif isinstance(self.adapter, BaseAsyncAdapter):
            self.__run_async = True
        else:
            raise ConfigurationError(
                "Adapter %r must extend either BaseSyncAdapter or BaseAsyncAdapter"
                % (type(self.adapter), ))
Example #16
0
    def __init__(
        self,
        format_string=None,
        scheme=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        ssl_context=DEFAULT_SENTINEL,
    ):
        if format_string is not None or options.default_format_string != "%s":
            warnings.warn(
                '`format_string` is deprecated. Please pass the already '
                'formatted queries to `geocode` instead. See '
                '`Specifying Parameters Once` section in docs for more '
                'details. In geopy 2.0 `format_string` will be removed.',
                DeprecationWarning,
                stacklevel=3)
        self.format_string = format_string or options.default_format_string
        self.scheme = scheme or options.default_scheme
        if self.scheme not in ('http', 'https'):
            raise ConfigurationError(
                'Supported schemes are `http` and `https`.')
        self.timeout = (timeout if timeout is not DEFAULT_SENTINEL else
                        options.default_timeout)
        self.proxies = (proxies if proxies is not DEFAULT_SENTINEL else
                        options.default_proxies)
        self.headers = {'User-Agent': user_agent or options.default_user_agent}
        self.ssl_context = (ssl_context if ssl_context is not DEFAULT_SENTINEL
                            else options.default_ssl_context)

        if isinstance(self.proxies, string_compare):
            self.proxies = {'http': self.proxies, 'https': self.proxies}

        # `ProxyHandler` should be present even when actually there're
        # no proxies. `build_opener` contains it anyway. By specifying
        # it here explicitly we can disable system proxies (i.e.
        # from HTTP_PROXY env var) by setting `self.proxies` to `{}`.
        # Otherwise, if we didn't specify ProxyHandler for empty
        # `self.proxies` here, build_opener would have used one internally
        # which could have unwillingly picked up the system proxies.
        opener = build_opener_with_context(
            self.ssl_context,
            ProxyHandler(self.proxies),
        )
        self.urlopen = opener.open
Example #17
0
    def __init__(
            self,
            format_string=None,
            scheme=None,
            timeout=DEFAULT_SENTINEL,
            proxies=DEFAULT_SENTINEL,
            user_agent=None,
            ssl_context=DEFAULT_SENTINEL,
    ):
        """
        Mostly-common geocoder validation, proxies, &c. Not all geocoders
        specify format_string and such.
        """
        self.format_string = format_string or options.default_format_string
        self.scheme = scheme or options.default_scheme
        if self.scheme not in ('http', 'https'):
            raise ConfigurationError(
                'Supported schemes are `http` and `https`.'
            )
        self.timeout = (timeout if timeout is not DEFAULT_SENTINEL
                        else options.default_timeout)
        self.proxies = (proxies if proxies is not DEFAULT_SENTINEL
                        else options.default_proxies)
        self.headers = {'User-Agent': user_agent or options.default_user_agent}
        self.ssl_context = (ssl_context if ssl_context is not DEFAULT_SENTINEL
                            else options.default_ssl_context)

        if isinstance(self.proxies, string_compare):
            self.proxies = {'http': self.proxies, 'https': self.proxies}

        # `ProxyHandler` should be present even when actually there're
        # no proxies. `build_opener` contains it anyway. By specifying
        # it here explicitly we can disable system proxies (i.e.
        # from HTTP_PROXY env var) by setting `self.proxies` to `{}`.
        # Otherwise, if we didn't specify ProxyHandler for empty
        # `self.proxies` here, build_opener would have used one internally
        # which could have unwillingly picked up the system proxies.
        opener = build_opener_with_context(
            self.ssl_context,
            ProxyHandler(self.proxies),
        )
        self.urlopen = opener.open
Example #18
0
    def __init__(self,
                 format_string=DEFAULT_FORMAT_STRING,
                 scheme=DEFAULT_SCHEME,
                 timeout=DEFAULT_TIMEOUT,
                 proxies=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

        if self.proxies:
            install_opener(build_opener(ProxyHandler(self.proxies)))
        self.urlopen = urllib_urlopen
Example #19
0
    def __init__(
            self,
            username=None,
            password=None,  # pylint: disable=R0913
            format_string=DEFAULT_FORMAT_STRING,
            timeout=DEFAULT_TIMEOUT,
            proxies=None):
        """
        :param string username:

        :param string password:

        :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 int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising an :class:`geopy.exc.GeocoderTimedOut`
            exception.

            .. versionadded:: 0.97

        :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`.

            .. versionadded:: 0.96
        """
        super(GeocoderDotUS, self).__init__(format_string=format_string,
                                            timeout=timeout,
                                            proxies=proxies)
        if username and password is None:
            raise ConfigurationError(
                "Password must be specified with username")
        self.username = username
        self.__password = password
Example #20
0
    def __init__(
        self,
        *,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        domain=_DEFAULT_NOMINATIM_DOMAIN,
        scheme=None,
        user_agent=None,
        ssl_context=DEFAULT_SENTINEL,
        adapter_factory=None
        # Make sure to synchronize the changes of this signature in the
        # inheriting classes (e.g. PickPoint).
    ):
        """

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str domain: Domain where the target Nominatim service
            is hosted.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

        :param callable adapter_factory:
            See :attr:`geopy.geocoders.options.default_adapter_factory`.

            .. versionadded:: 2.0
        """
        super().__init__(
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
            adapter_factory=adapter_factory,
        )

        self.domain = domain.strip('/')

        if (self.domain == _DEFAULT_NOMINATIM_DOMAIN
                and self.headers['User-Agent'] in _REJECTED_USER_AGENTS):
            raise ConfigurationError(
                'Using Nominatim with default or sample `user_agent` "%s" is '
                'strongly discouraged, as it violates Nominatim\'s ToS '
                'https://operations.osmfoundation.org/policies/nominatim/ '
                'and may possibly cause 403 and 429 HTTP errors. '
                'Please specify a custom `user_agent` with '
                '`Nominatim(user_agent="my-application")` or by '
                'overriding the default `user_agent`: '
                '`geopy.geocoders.options.default_user_agent = "my-application"`.'
                % self.headers['User-Agent'])

        self.api = "%s://%s%s" % (self.scheme, self.domain, self.geocode_path)
        self.reverse_api = "%s://%s%s" % (self.scheme, self.domain,
                                          self.reverse_path)
Example #21
0
    def __init__(
        self,
        auth_id,
        auth_token,
        candidates=1,
        scheme='https',
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        format_string=None,
        ssl_context=DEFAULT_SENTINEL,
    ):
        """

        :param str auth_id: Valid `Auth ID` from SmartyStreets.

            .. versionadded:: 1.5.0

        :param str auth_token: Valid `Auth Token` from SmartyStreets.

        :param int candidates: An integer between 1 and 10 indicating the max
            number of candidate addresses to return if a valid address
            could be found.

        :param str scheme: Must be ``https``.

            .. deprecated:: 1.14.0
               Don't use this parameter, it's going to be removed in
               geopy 2.0.

            .. versionchanged:: 1.8.0
               LiveAddress now requires `https`. Specifying `scheme=http` will
               result in a :class:`geopy.exc.ConfigurationError`.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

            .. versionadded:: 1.14.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0
        """
        super(LiveAddress, self).__init__(
            format_string=format_string,
            # The `scheme` argument is present for the legacy reasons only.
            # If a custom value has been passed, it should be validated.
            # Otherwise use `https` instead of the `options.default_scheme`.
            scheme=(scheme or 'https'),
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if self.scheme != "https":
            raise ConfigurationError("LiveAddress now requires `https`.")
        self.auth_id = auth_id
        self.auth_token = auth_token
        if candidates:
            if not (1 <= candidates <= 10):
                raise ValueError('candidates must be between 1 and 10')
        self.candidates = candidates
        domain = 'api.smartystreets.com'
        self.api = '%s://%s%s' % (self.scheme, domain, self.geocode_path)
Example #22
0
    def __init__(
            self,
            username=None,
            password=None,
            referer=None,  # pylint: disable=R0913
            token_lifetime=60,
            scheme=DEFAULT_SCHEME,
            timeout=DEFAULT_TIMEOUT,
            proxies=None,
            user_agent=None,
            temparray=[]):
        """
        Create a ArcGIS-based geocoder.

            .. versionadded:: 0.97

        :param string username: ArcGIS username. Required if authenticated
            mode is desired.

        :param string password: ArcGIS password. Required if authenticated
            mode is desired.

        :param string referer: Required if authenticated mode is desired.
            'Referer' HTTP header to send with each request,
            e.g., 'http://www.example.com'. This is tied to an issued token,
            so fielding queries for multiple referrers should be handled by
            having multiple ArcGIS geocoder instances.

        :param int token_lifetime: Desired lifetime, in minutes, of an
            ArcGIS-issued token.

        :param string scheme: Desired scheme. If authenticated mode is in use,
            it must be 'https'.

        :param int timeout: Time, in seconds, to wait for the geocoding service
            to respond before raising a :class:`geopy.exc.GeocoderTimedOut`
            exception.

        :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`.
        """
        super(ArcGIS, self).__init__(scheme=scheme,
                                     timeout=timeout,
                                     proxies=proxies,
                                     user_agent=user_agent)
        if username or password or referer:
            if not (username and password and referer):
                raise ConfigurationError(
                    "Authenticated mode requires username,"
                    " password, and referer")
            if self.scheme != 'https':
                raise ConfigurationError(
                    "Authenticated mode requires scheme of 'https'")
            self._base_call_geocoder = self._call_geocoder
            self._call_geocoder = self._authenticated_call_geocoder

        self.username = username
        self.password = password
        self.referer = referer

        self.token = None
        self.token_lifetime = token_lifetime * 60  # store in seconds
        self.token_expiry = None
        self.retry = 1

        self.api = ('%s://geocode.arcgis.com/arcgis/rest/services/'
                    'World/GeocodeServer/find' % self.scheme)
        self.api_multi = ('%s://geocode.arcgis.com/arcgis/rest/services/'
                          'World/GeocodeServer/findAddressCandidates' %
                          self.scheme)
        self.reverse_api = ('%s://geocode.arcgis.com/arcgis/rest/services/'
                            'World/GeocodeServer/reverseGeocode' % self.scheme)
Example #23
0
    def __init__(
        self,
        api_key=None,
        format_string=None,
        view_box=None,
        bounded=False,
        country_bias=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        domain='open.mapquestapi.com',
        scheme=None,
        user_agent=None,
        ssl_context=DEFAULT_SENTINEL,
    ):
        """

        :param str api_key: API key provided by MapQuest, required.

            .. versionchanged:: 1.12.0
               OpenMapQuest now requires an API key. Using an empty key will
               result in a :class:`geopy.exc.ConfigurationError`.

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

        :type view_box: list or tuple of 2 items of :class:`geopy.point.Point` or
            ``(latitude, longitude)`` or ``"%(latitude)s, %(longitude)s"``.
        :param view_box: Coordinates to restrict search within.
            Example: ``[Point(22, 180), Point(-22, -180)]``.

            .. versionadded:: 1.17.0

        :param bool bounded: Restrict the results to only items contained
            within the bounding view_box.

            .. versionadded:: 1.17.0

        :param str country_bias: Bias results to this country.

            .. versionadded:: 1.17.0

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str domain: Domain where the target Nominatim service
            is hosted.

            .. versionadded:: 1.17.0

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0
        """
        super(OpenMapQuest, self).__init__(
            format_string=format_string,
            view_box=view_box,
            bounded=bounded,
            country_bias=country_bias,
            timeout=timeout,
            proxies=proxies,
            domain=domain,
            scheme=scheme,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if not api_key:
            raise ConfigurationError('OpenMapQuest requires an API key')
        self.api_key = api_key
Example #24
0
    def __init__(
        self,
        api_key=None,
        domain='maps.googleapis.com',
        scheme=None,
        client_id=None,
        secret_key=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        format_string=None,
        ssl_context=DEFAULT_SENTINEL,
        channel='',
    ):
        """

        :param str api_key: The API key required by Google to perform
            geocoding requests. API keys are managed through the Google APIs
            console (https://code.google.com/apis/console).

        :param str domain: Should be the localized Google Maps domain to
            connect to. The default is 'maps.googleapis.com', but if you're
            geocoding address in the UK (for example), you may want to set it
            to 'maps.google.co.uk' to properly bias results.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param str client_id: If using premier, the account client id.

        :param str secret_key: If using premier, the account secret key.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

            .. versionadded:: 1.14.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0

        :param str channel: If using premier, the channel identifier.

            .. versionadded:: 1.12.0
        """
        super(GoogleV3, self).__init__(
            format_string=format_string,
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if client_id and not secret_key:
            raise ConfigurationError('Must provide secret_key with client_id.')
        if secret_key and not client_id:
            raise ConfigurationError('Must provide client_id with secret_key.')

        self.api_key = api_key
        self.domain = domain.strip('/')

        self.premier = bool(client_id and secret_key)
        self.client_id = client_id
        self.secret_key = secret_key
        self.channel = channel

        self.api = '%s://%s/maps/api/geocode/json' % (self.scheme, self.domain)
        self.tz_api = '%s://%s/maps/api/timezone/json' % (self.scheme,
                                                          self.domain)
Example #25
0
    def __init__(self,
                 api_key=None,
                 domain='maps.googleapis.com',
                 scheme=DEFAULT_SCHEME,
                 client_id=None,
                 secret_key=None,
                 timeout=DEFAULT_TIMEOUT,
                 proxies=None,
                 user_agent=None,
                 channel='',
                 temparray=[]):  # pylint: disable=R0913
        """
        Initialize a customized Google geocoder.

        API authentication is only required for Google Maps Premier customers.

        :param string api_key: The API key required by Google to perform
            geocoding requests. API keys are managed through the Google APIs
            console (https://code.google.com/apis/console).

            .. versionadded:: 0.98.2

        :param string domain: Should be the localized Google Maps domain to
            connect to. The default is 'maps.googleapis.com', but if you're
            geocoding address in the UK (for example), you may want to set it
            to 'maps.google.co.uk' to properly bias results.

        :param string scheme: Use 'https' or 'http' as the API URL's scheme.
            Default is https. Note that SSL connections' certificates are not
            verified.

            .. versionadded:: 0.97

        :param string client_id: If using premier, the account client id.

        :param string secret_key: If using premier, the account secret key.

        :param string channel: If using premier, the channel identifier.

        :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`.

            .. versionadded:: 0.96
        """
        super(GoogleV3, self).__init__(scheme=scheme,
                                       timeout=timeout,
                                       proxies=proxies,
                                       user_agent=user_agent)
        if client_id and not secret_key:
            raise ConfigurationError('Must provide secret_key with client_id.')
        if secret_key and not client_id:
            raise ConfigurationError('Must provide client_id with secret_key.')

        self.api_key = api_key
        self.domain = domain.strip('/')
        self.scheme = scheme
        self.doc = {}

        self.premier = bool(client_id and secret_key)
        self.client_id = client_id
        self.secret_key = secret_key
        self.channel = channel

        self.api = '%s://%s/maps/api/geocode/json' % (self.scheme, self.domain)
        self.tz_api = '%s://%s/maps/api/timezone/json' % (self.scheme,
                                                          self.domain)
Example #26
0
    def __init__(self,
                 api_key,
                 *,
                 username=None,
                 password=None,
                 referer=None,
                 domain='wxs.ign.fr',
                 scheme=None,
                 timeout=DEFAULT_SENTINEL,
                 proxies=DEFAULT_SENTINEL,
                 user_agent=None,
                 ssl_context=DEFAULT_SENTINEL,
                 adapter_factory=None):
        """

        :param str api_key: The API key required by IGN France API
            to perform geocoding requests. You can get your key here:
            https://geoservices.ign.fr/documentation/services-acces.html.
            Mandatory. For authentication with referer
            and with username/password, the api key always differ.

        :param str username: When making a call need HTTP simple
            authentication username. Mandatory if no referer set

        :param str password: When making a call need HTTP simple
            authentication password. Mandatory if no referer set

        :param str referer: When making a call need HTTP referer.
            Mandatory if no password and username

        :param str domain: Currently it is ``'wxs.ign.fr'``, can
            be changed for testing purposes for developer API
            e.g ``'gpp3-wxs.ign.fr'`` at the moment.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

        :param callable adapter_factory:
            See :attr:`geopy.geocoders.options.default_adapter_factory`.

            .. versionadded:: 2.0
        """
        super().__init__(
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
            adapter_factory=adapter_factory,
        )

        # Catch if no api key with username and password
        # or no api key with referer
        if not ((api_key and username and password) or (api_key and referer)):
            raise ConfigurationError('You should provide an api key and a '
                                     'username with a password or an api '
                                     'key with a referer depending on '
                                     'created api key')
        if (username and password) and referer:
            raise ConfigurationError('You can\'t set username/password and '
                                     'referer together. The API key always '
                                     'differs depending on both scenarios')
        if username and not password:
            raise ConfigurationError(
                'username and password must be set together')

        self.api_key = api_key
        self.username = username
        self.password = password
        self.referer = referer
        self.domain = domain.strip('/')
        api_path = self.api_path % dict(api_key=self.api_key)
        self.api = '%s://%s%s' % (self.scheme, self.domain, api_path)
Example #27
0
    def __init__(self,
                 api_key=None,
                 *,
                 domain='maps.googleapis.com',
                 scheme=None,
                 client_id=None,
                 secret_key=None,
                 timeout=DEFAULT_SENTINEL,
                 proxies=DEFAULT_SENTINEL,
                 user_agent=None,
                 ssl_context=DEFAULT_SENTINEL,
                 adapter_factory=None,
                 channel=''):
        """

        :param str api_key: The API key required by Google to perform
            geocoding requests, mandatory (unless premier is used,
            then both ``client_id`` and ``secret_key`` must be specified
            instead).
            API keys are managed through
            the Google APIs console (https://code.google.com/apis/console).
            Make sure to have both ``Geocoding API`` and ``Time Zone API``
            services enabled for this API key.

            .. versionchanged:: 2.1
               Previously a warning has been emitted when neither ``api_key``
               nor premier were specified. Now a :class:`geopy.exc.ConfigurationError`
               is raised.

        :param str domain: Should be the localized Google Maps domain to
            connect to. The default is 'maps.googleapis.com', but if you're
            geocoding address in the UK (for example), you may want to set it
            to 'maps.google.co.uk' to properly bias results.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param str client_id: If using premier, the account client id.

        :param str secret_key: If using premier, the account secret key.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

        :param callable adapter_factory:
            See :attr:`geopy.geocoders.options.default_adapter_factory`.

            .. versionadded:: 2.0

        :param str channel: If using premier, the channel identifier.
        """
        super().__init__(
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
            adapter_factory=adapter_factory,
        )
        if client_id and not secret_key:
            raise ConfigurationError('Must provide secret_key with client_id.')
        if secret_key and not client_id:
            raise ConfigurationError('Must provide client_id with secret_key.')

        self.premier = bool(client_id and secret_key)
        self.client_id = client_id
        self.secret_key = secret_key

        if not self.premier and not api_key:
            raise ConfigurationError(
                'Since July 2018 Google requires each request to have an API key. '
                'Pass a valid `api_key` to GoogleV3 geocoder to fix this error. '
                'See https://developers.google.com/maps/documentation/geocoding/usage-and-billing'  # noqa
            )

        self.api_key = api_key
        self.domain = domain.strip('/')

        self.channel = channel

        self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path)
        self.tz_api = '%s://%s%s' % (self.scheme, self.domain,
                                     self.timezone_path)
Example #28
0
    def __init__(
        self,
        api_key=None,
        domain='maps.googleapis.com',
        scheme=None,
        client_id=None,
        secret_key=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        format_string=None,
        ssl_context=DEFAULT_SENTINEL,
        channel='',
    ):
        """

        :param str api_key: The API key required by Google to perform
            geocoding requests. API keys are managed through the Google APIs
            console (https://code.google.com/apis/console).
            Make sure to have both ``Geocoding API`` and ``Time Zone API``
            services enabled for this API key.

        :param str domain: Should be the localized Google Maps domain to
            connect to. The default is 'maps.googleapis.com', but if you're
            geocoding address in the UK (for example), you may want to set it
            to 'maps.google.co.uk' to properly bias results.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param str client_id: If using premier, the account client id.

        :param str secret_key: If using premier, the account secret key.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

            .. versionadded:: 1.14.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0

        :param str channel: If using premier, the channel identifier.

            .. versionadded:: 1.12.0
        """
        super(GoogleV3, self).__init__(
            format_string=format_string,
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if client_id and not secret_key:
            raise ConfigurationError('Must provide secret_key with client_id.')
        if secret_key and not client_id:
            raise ConfigurationError('Must provide client_id with secret_key.')

        if not api_key:
            warnings.warn(
                'Since July 2018 Google requires each request to have an API key. '
                'Pass a valid `api_key` to GoogleV3 geocoder to hide this warning. '
                'See https://developers.google.com/maps/documentation/geocoding/usage-and-billing',  # noqa
                UserWarning,
                stacklevel=2)

        self.api_key = api_key
        self.domain = domain.strip('/')

        self.premier = bool(client_id and secret_key)
        self.client_id = client_id
        self.secret_key = secret_key
        self.channel = channel

        self.api = '%s://%s%s' % (self.scheme, self.domain, self.api_path)
        self.tz_api = '%s://%s%s' % (self.scheme, self.domain,
                                     self.timezone_path)
Example #29
0
    def __init__(self,
                 *,
                 app_id=None,
                 app_code=None,
                 apikey=None,
                 scheme=None,
                 timeout=DEFAULT_SENTINEL,
                 proxies=DEFAULT_SENTINEL,
                 user_agent=None,
                 ssl_context=DEFAULT_SENTINEL,
                 adapter_factory=None):
        """

        :param str app_id: Should be a valid HERE Maps APP ID. Will eventually
            be replaced with APIKEY.
            See https://developer.here.com/authenticationpage.

            .. attention::
                App ID and App Code are being replaced by API Keys and OAuth 2.0
                by HERE. Consider getting an ``apikey`` instead of using
                ``app_id`` and ``app_code``.

        :param str app_code: Should be a valid HERE Maps APP CODE. Will
            eventually be replaced with APIKEY.
            See https://developer.here.com/authenticationpage.

            .. attention::
                App ID and App Code are being replaced by API Keys and OAuth 2.0
                by HERE. Consider getting an ``apikey`` instead of using
                ``app_id`` and ``app_code``.

        :param str apikey: Should be a valid HERE Maps APIKEY. These keys were
            introduced in December 2019 and will eventually replace the legacy
            APP CODE/APP ID pairs which are already no longer available for new
            accounts (but still work for old accounts).
            More authentication details are available at
            https://developer.here.com/blog/announcing-two-new-authentication-types.
            See https://developer.here.com/authenticationpage.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

        :param callable adapter_factory:
            See :attr:`geopy.geocoders.options.default_adapter_factory`.

            .. versionadded:: 2.0
        """
        super().__init__(
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
            adapter_factory=adapter_factory,
        )
        is_apikey = bool(apikey)
        is_app_code = app_id and app_code
        if not is_apikey and not is_app_code:
            raise ConfigurationError(
                "HERE geocoder requires authentication, either `apikey` "
                "or `app_id`+`app_code` must be set")
        if is_app_code:
            warnings.warn(
                'Since December 2019 HERE provides two new authentication '
                'methods `API Key` and `OAuth 2.0`. `app_id`+`app_code` '
                'is deprecated and might eventually be phased out. '
                'Consider switching to `apikey`, which geopy supports. '
                'See https://developer.here.com/blog/announcing-two-new-authentication-types',  # noqa
                UserWarning,
                stacklevel=2)

        self.app_id = app_id
        self.app_code = app_code
        self.apikey = apikey
        domain = "ls.hereapi.com" if is_apikey else "api.here.com"
        self.api = "%s://geocoder.%s%s" % (self.scheme, domain,
                                           self.geocode_path)
        self.reverse_api = ("%s://reverse.geocoder.%s%s" %
                            (self.scheme, domain, self.reverse_path))
Example #30
0
    def __init__(
        self,
        username=None,
        password=None,
        referer=None,
        token_lifetime=60,
        scheme=None,
        timeout=DEFAULT_SENTINEL,
        proxies=DEFAULT_SENTINEL,
        user_agent=None,
        format_string=None,
        ssl_context=DEFAULT_SENTINEL,
        auth_domain='www.arcgis.com',
        domain='geocode.arcgis.com',
    ):
        """

        :param str username: ArcGIS username. Required if authenticated
            mode is desired.

        :param str password: ArcGIS password. Required if authenticated
            mode is desired.

        :param str referer: Required if authenticated mode is desired.
            `Referer` HTTP header to send with each request,
            e.g., ``'http://www.example.com'``. This is tied to an issued token,
            so fielding queries for multiple referrers should be handled by
            having multiple ArcGIS geocoder instances.

        :param int token_lifetime: Desired lifetime, in minutes, of an
            ArcGIS-issued token.

        :param str scheme:
            See :attr:`geopy.geocoders.options.default_scheme`.
            If authenticated mode is in use, it must be ``'https'``.

        :param int timeout:
            See :attr:`geopy.geocoders.options.default_timeout`.

        :param dict proxies:
            See :attr:`geopy.geocoders.options.default_proxies`.

        :param str user_agent:
            See :attr:`geopy.geocoders.options.default_user_agent`.

            .. versionadded:: 1.12.0

        :param str format_string:
            See :attr:`geopy.geocoders.options.default_format_string`.

            .. versionadded:: 1.14.0

        :type ssl_context: :class:`ssl.SSLContext`
        :param ssl_context:
            See :attr:`geopy.geocoders.options.default_ssl_context`.

            .. versionadded:: 1.14.0

        :param str auth_domain: Domain where the target ArcGIS auth service
            is hosted. Used only in authenticated mode (i.e. username,
            password and referer are set).

            .. versionadded:: 1.17.0

        :param str domain: Domain where the target ArcGIS service
            is hosted.

            .. versionadded:: 1.17.0
        """
        super(ArcGIS, self).__init__(
            format_string=format_string,
            scheme=scheme,
            timeout=timeout,
            proxies=proxies,
            user_agent=user_agent,
            ssl_context=ssl_context,
        )
        if username or password or referer:
            if not (username and password and referer):
                raise ConfigurationError(
                    "Authenticated mode requires username,"
                    " password, and referer")
            if self.scheme != 'https':
                raise ConfigurationError(
                    "Authenticated mode requires scheme of 'https'")
            self._base_call_geocoder = self._call_geocoder
            self._call_geocoder = self._authenticated_call_geocoder

        self.username = username
        self.password = password
        self.referer = referer
        self.auth_domain = auth_domain.strip('/')
        self.auth_api = ('%s://%s%s' %
                         (self.scheme, self.auth_domain, self.auth_path))

        self.token = None
        self.token_lifetime = token_lifetime * 60  # store in seconds
        self.token_expiry = None
        self.retry = 1

        self.domain = domain.strip('/')
        self.api = ('%s://%s%s' %
                    (self.scheme, self.domain, self.geocode_path))
        self.reverse_api = ('%s://%s%s' %
                            (self.scheme, self.domain, self.reverse_path))