Exemplo n.º 1
0
 def _refresh_authentication_token_broken(self):
     """
     POST to ArcGIS requesting a new token.
     """
     if self.retry == self._MAX_RETRIES:
         raise GeocoderAuthenticationFailure(
             'Too many retries for auth: %s' % self.retry)
     token_request_arguments = {
         'username': self.username,
         'password': self.password,
         'client': 'requestip',
         #'referer': 'requestip',
         'expiration': self.token_lifetime,
         'f': 'json'
     }
     self.token_expiry = int(time()) + self.token_lifetime
     data = urlencode(token_request_arguments)
     print(data)
     data = data.encode("utf-8")
     print(data)
     req = Request(url=self.auth_api, headers=self.headers)
     print(req)
     page = urlopen(req, data=data, timeout=self.timeout)
     print(page)
     page = page.read()
     print(page)
     response = json.loads(page.decode('unicode_escape'))
     if not 'token' in response:
         raise GeocoderAuthenticationFailure(
             'Missing token in auth request. '
             'Request URL: %s?%s. '
             'Response JSON: %s. ' %
             (self.auth_api, data, json.dumps(response)))
     self.retry = 0
     self.token = response['token']
Exemplo n.º 2
0
 def _refresh_authentication_token(self):
     """
     POST to ArcGIS requesting a new token.
     """
     if self.retry == self._MAX_RETRIES:
         raise GeocoderAuthenticationFailure(
             'Too many retries for auth: %s' % self.retry)
     token_request_arguments = {
         'username': self.username,
         'password': self.password,
         'expiration': self.token_lifetime,
         'f': 'json'
     }
     token_request_arguments = "&".join([
         "%s=%s" % (key, val)
         for key, val in token_request_arguments.items()
     ])
     url = "&".join(("?".join((self.auth_api, token_request_arguments)),
                     urlencode({'referer': self.referer})))
     logger.debug("%s._refresh_authentication_token: %s",
                  self.__class__.__name__, url)
     self.token_expiry = int(time()) + self.token_lifetime
     response = self._base_call_geocoder(url)
     if not 'token' in response:
         raise GeocoderAuthenticationFailure(
             'Missing token in auth request.'
             'Request URL: %s; response JSON: %s' %
             (url, json.dumps(response)))
     self.retry = 0
     self.token = response['token']
Exemplo n.º 3
0
 def _call_geocoder(self, url, timeout=None, raw=False):
     """
     For a generated query URL, get the results.
     """
     try:
         page = self.urlopen(url, timeout=timeout or self.timeout)
     except Exception as error:  # pylint: disable=W0703
         if hasattr(self, '_geocoder_exception_handler'):
             self._geocoder_exception_handler(error)  # pylint: disable=E1101
         if isinstance(error, HTTPError):
             if error.msg.lower().contains("unauthorized"):
                 raise GeocoderAuthenticationFailure("Unauthorized")
             raise GeocoderServiceError(error.getcode(), error.msg)
         elif isinstance(error, URLError):
             if "timed out" in error.reason:
                 raise GeocoderTimedOut('Service timed out')
             raise
         elif isinstance(error, SocketTimeout):
             raise GeocoderTimedOut('Service timed out')
         elif isinstance(error, SSLError):
             if error.message == 'The read operation timed out':
                 raise GeocoderTimedOut('Service timed out')
             raise
         else:
             raise
     if raw:
         return page
     return json.loads(decode_page(page))
Exemplo n.º 4
0
 def _check_status(status):
     """
     Validates error statuses.
     """
     if status == '0':
         # When there are no results, just return.
         return
     if status == '1':
         raise GeocoderQueryError('Internal server error.')
     elif status == '2':
         raise GeocoderQueryError('Invalid request.')
     elif status == '3':
         raise GeocoderAuthenticationFailure('Authentication failure.')
     elif status == '4':
         raise GeocoderQuotaExceeded('Quota validate failure.')
     elif status == '5':
         raise GeocoderQueryError('AK Illegal or Not Exist.')
     elif status == '101':
         raise GeocoderQueryError('Your request was denied.')
     elif status == '102':
         raise GeocoderQueryError('IP/SN/SCODE/REFERER Illegal:')
     elif status == '2xx':
         raise GeocoderQueryError('Has No Privilleges.')
     elif status == '3xx':
         raise GeocoderQuotaExceeded('Quota Error.')
     else:
         raise GeocoderQueryError('Unknown error')
Exemplo n.º 5
0
 def cb(response):
     if "token" not in response:
         raise GeocoderAuthenticationFailure(
             "Missing token in auth request."
             "Request URL: %s; response JSON: %s" %
             (url, json.dumps(response)))
     self.token = response["token"]
     self.token_expiry = int(time()) + self.token_lifetime
     return callback_success()
Exemplo n.º 6
0
 def _check_status(status):
     """
     Validates error statuses.
     """
     if status == 0:
         # When there are no results, just return.
         return
     if status == 1:
         raise GeocoderServiceError('Internal server error.')
     elif status == 2:
         raise GeocoderQueryError('Invalid request.')
     elif status == 3:
         raise GeocoderAuthenticationFailure('Authentication failure.')
     elif status == 4:
         raise GeocoderQuotaExceeded('Quota validate failure.')
     elif status == 5:
         raise GeocoderQueryError('AK Illegal or Not Exist.')
     elif status == 101:
         raise GeocoderAuthenticationFailure('No AK')
     elif status == 102:
         raise GeocoderAuthenticationFailure('MCODE Error')
     elif status == 200:
         raise GeocoderAuthenticationFailure('Invalid AK')
     elif status == 211:
         raise GeocoderAuthenticationFailure('Invalid SN')
     elif 200 <= status < 300:
         raise GeocoderAuthenticationFailure('Authentication Failure')
     elif 300 <= status < 500:
         raise GeocoderQuotaExceeded('Quota Error.')
     else:
         raise GeocoderQueryError('Unknown error. Status: %r' % status)
Exemplo n.º 7
0
    def _parse_json(self, doc, exactly_one=True):
        """
        Parse a location name, latitude, and longitude from an JSON response.
        """
        status_code = doc.get("statusCode", 200)
        if status_code != 200:
            err = doc.get("errorDetails", "")
            if status_code == 401:
                raise GeocoderAuthenticationFailure(err)
            elif status_code == 403:
                raise GeocoderInsufficientPrivileges(err)
            elif status_code == 429:
                raise GeocoderRateLimited(err)
            elif status_code == 503:
                raise GeocoderUnavailable(err)
            else:
                raise GeocoderServiceError(err)

        try:
            resources = doc['Response']['View'][0]['Result']
        except IndexError:
            resources = None
        if not resources:
            return None

        def parse_resource(resource):
            """
            Parse each return object.
            """
            stripchars = ", \n"
            addr = resource['Location']['Address']

            address = addr.get('Label', '').strip(stripchars)
            city = addr.get('City', '').strip(stripchars)
            state = addr.get('State', '').strip(stripchars)
            zipcode = addr.get('PostalCode', '').strip(stripchars)
            country = addr.get('Country', '').strip(stripchars)

            city_state = join_filter(", ", [city, state])
            place = join_filter(" ", [city_state, zipcode])
            location = join_filter(", ", [address, place, country])

            display_pos = resource['Location']['DisplayPosition']
            latitude = float(display_pos['Latitude'])
            longitude = float(display_pos['Longitude'])

            return Location(location, (latitude, longitude), resource)

        if exactly_one:
            return parse_resource(resources[0])
        else:
            return [parse_resource(resource) for resource in resources]
Exemplo n.º 8
0
 def _raise_for_error(self, body):
     err = body.get('status')
     if err:
         code = err['value']
         message = err['message']
         # http://www.geonames.org/export/webservice-exception.html
         if message.startswith("user account not enabled to use"):
             raise GeocoderInsufficientPrivileges(message)
         if code == 10:
             raise GeocoderAuthenticationFailure(message)
         if code in (18, 19, 20):
             raise GeocoderQuotaExceeded(message)
         raise GeocoderServiceError(message)
    def _parse_json(doc, exactly_one=True):  # pylint: disable=W0221
        """
        Parse a location name, latitude, and longitude from an JSON response.
        """
        status_code = doc.get("statusCode", 200)
        if status_code != 200:
            err = doc.get("errorDetails", "")
            if status_code == 401:
                raise GeocoderAuthenticationFailure(err)
            elif status_code == 403:
                raise GeocoderInsufficientPrivileges(err)
            elif status_code == 429:
                raise GeocoderQuotaExceeded(err)
            elif status_code == 503:
                raise GeocoderUnavailable(err)
            else:
                raise GeocoderServiceError(err)

        resources = doc['resourceSets'][0]['resources']
        if resources is None or not len(resources):  # pragma: no cover
            return None

        def parse_resource(resource):
            """
            Parse each return object.
            """
            stripchars = ", \n"
            addr = resource['address']

            address = addr.get('addressLine', '').strip(stripchars)
            city = addr.get('locality', '').strip(stripchars)
            state = addr.get('adminDistrict', '').strip(stripchars)
            zipcode = addr.get('postalCode', '').strip(stripchars)
            country = addr.get('countryRegion', '').strip(stripchars)

            city_state = join_filter(", ", [city, state])
            place = join_filter(" ", [city_state, zipcode])
            location = join_filter(", ", [address, place, country])

            latitude = resource['point']['coordinates'][0] or None
            longitude = resource['point']['coordinates'][1] or None
            if latitude and longitude:
                latitude = float(latitude)
                longitude = float(longitude)

            return Location(location, (latitude, longitude), resource)

        if exactly_one:
            return parse_resource(resources[0])
        else:
            return [parse_resource(resource) for resource in resources]
Exemplo n.º 10
0
 def _check_status(status):
     """
     Validates error statuses.
     """
     if status == 0:
         # When there are no results, just return.
         return
     if status == 110:
         raise GeocoderQueryError(u'请求来源未被授权.')
     elif status == 306:
         raise GeocoderQueryError(u'请求有护持信息请检查字符串.')
     elif status == 310:
         raise GeocoderAuthenticationFailure(u'请求参数信息有误.')
     elif status == 311:
         raise GeocoderQuotaExceeded(u'key格式错误.')
     else:
         raise GeocoderQueryError('Unknown error: %s' % status)
Exemplo n.º 11
0
 def _check_status(status):
     """
     Validates error statuses.
     """
     if status == '10000':
         # When there are no results, just return.
         return
     if status == '10001':
         raise GeocoderAuthenticationFailure('Invalid user key.')
     elif status == '10002':
         raise GeocoderAuthenticationFailure('Service not available.')
     elif status == '10003':
         raise GeocoderQuotaExceeded('Daily query over limit.')
     elif status == '10004':
         raise GeocoderQuotaExceeded('Access too frequent.')
     elif status == '10005':
         raise GeocoderQueryError('Invalid user IP.')
     elif status == '10006':
         raise GeocoderQueryError('Invalid user domain.')
     elif status == '10007':
         raise GeocoderQueryError('Invalid user signature')
     elif status == '10008':
         raise GeocoderQueryError('Invalid user scode.')
     elif status == '10009':
         raise GeocoderQuotaExceeded('Userkey plat nomatch.')
     elif status == '10010':
         raise GeocoderQuotaExceeded('IP query over limit.')
     elif status == '10011':
         raise GeocoderQuotaExceeded('Not support https.')
     elif status == '10012':
         raise GeocoderQuotaExceeded('Insufficient privileges.')
     elif status == '10013':
         raise GeocoderQuotaExceeded('User key recycled.')
     elif status == '10014':
         raise GeocoderQuotaExceeded('QPS has exceeded the limit.')
     elif status == '10015':
         raise GeocoderQuotaExceeded('Gateway timeout.')
     elif status == '10016':
         raise GeocoderQuotaExceeded('Server is busy.')
     elif status == '10017':
         raise GeocoderQuotaExceeded('Resource unavailable.')
     elif status == '20000':
         raise GeocoderQuotaExceeded('Invalid params.')
     elif status == '20001':
         raise GeocoderQuotaExceeded('Missing required params.')
     elif status == '20002':
         raise GeocoderQuotaExceeded('Illegal request.')
     elif status == '20003':
         raise GeocoderQuotaExceeded('Unknown error.')
     elif status == '20800':
         raise GeocoderQuotaExceeded('Out of service.')
     elif status == '20801':
         raise GeocoderQuotaExceeded('No roads nearby.')
     elif status == '20802':
         raise GeocoderQuotaExceeded('Route fail.')
     elif status == '20803':
         raise GeocoderQuotaExceeded('Over direction range.')
     elif status == '300**':
         raise GeocoderQuotaExceeded('Engine response data error.')
     else:
         raise GeocoderQueryError('Unknown error')