Compare commits

...

45 Commits

Author SHA1 Message Date
Mario de Frutos
019df2b4e0 Merge pull request #451 from CartoDB/development
Hotfix circular dependencies exceptions
2018-02-02 12:38:23 +01:00
Mario de Frutos
9e67beab3d Merge pull request #450 from CartoDB/move_exceptions_to_avoid_circular_dependencies
Move exceptions to a proper place
2018-02-02 12:37:14 +01:00
Mario de Frutos
5c7d1e9ac1 Solve some dependencies bugs 2018-02-02 12:29:48 +01:00
Mario de Frutos
6e54507b5a Move exceptions to a proper place 2018-02-02 12:06:43 +01:00
Mario de Frutos
14925ea448 Add missing imports for google gecode street 2018-02-02 11:18:56 +01:00
Mario de Frutos
26e0a5e00f Merge pull request #448 from CartoDB/development
Release server 0.30.2 and python library 0.16.4
2018-02-02 10:37:16 +01:00
Mario de Frutos
a99e0cb513 Updated NEWS.md 2018-02-02 10:32:24 +01:00
Mario de Frutos
1e4fef5868 Merge pull request #447 from CartoDB/dont_send_quota_exceptions_rollbar
Avoid treating quota exception as bug exception
2018-02-02 10:29:04 +01:00
Mario de Frutos
3973483af2 Move limits check inside the try 2018-02-01 19:03:32 +01:00
Mario de Frutos
88edad9414 Release artifacts for version 0.30.2 2018-02-01 18:46:24 +01:00
Mario de Frutos
88ad551e4a Bump python version to 0.16.4 2018-02-01 18:40:21 +01:00
Mario de Frutos
94eaf84f91 Treat quota exception as a failure 2018-02-01 18:27:32 +01:00
Mario de Frutos
0df0b0d49c Avoid treating quota exception as bug exception 2018-02-01 18:21:15 +01:00
Mario de Frutos
b260c29b8c Merge pull request #445 from CartoDB/development
Updated routing documentation
2018-02-01 12:10:20 +01:00
Mario de Frutos
da8aa5a8c0 Merge pull request #444 from CartoDB/fix_routing_documentation
Change routing docs with the Mapbox addition as provider
2018-02-01 12:05:27 +01:00
Mario de Frutos
423534068a Change routing docs with the Mapbox addition as provider 2018-02-01 11:55:22 +01:00
Mario de Frutos
6f508b550d Merge pull request #441 from CartoDB/development
Release python library 0.16.3
2018-01-31 17:06:00 +01:00
Mario de Frutos
1462f87d97 Merge pull request #440 from CartoDB/439_filter_empty_requests_mapbox_geocoder
Improve empty requests treatment in geocoders
2018-01-31 16:31:11 +01:00
Mario de Frutos
6ae8aa45fd CR changes 2018-01-31 16:13:20 +01:00
Mario de Frutos
02cb4862f9 Update NEWS.md 2018-01-31 13:18:09 +01:00
Mario de Frutos
07f00cc0ae Added tests for the client/channel part of google 2018-01-31 13:17:36 +01:00
Mario de Frutos
544e0fa763 Going green with non empty request strings 2018-01-31 12:25:35 +01:00
Mario de Frutos
2bbd6bac91 Going red with non empty request string 2018-01-31 12:25:18 +01:00
Mario de Frutos
2f8dbbb5dc Dont raise exception when empty params passed to HERE geocoder 2018-01-31 12:16:13 +01:00
Mario de Frutos
3484cce88b Update NEWS.md 2018-01-31 12:13:02 +01:00
Mario de Frutos
56c90cc541 Bump version to 0.16.3 2018-01-31 12:12:52 +01:00
Mario de Frutos
3583cc6f47 Going green with empty requests that leads to 404 responses 2018-01-31 12:11:25 +01:00
Mario de Frutos
850dc09a4f Going green with empty responses 2018-01-31 12:11:25 +01:00
Mario de Frutos
876bae6b56 Going red with bad request parameters 2018-01-31 12:11:25 +01:00
Mario de Frutos
8f30359cc7 Added rate limits topic to the README 2018-01-30 15:02:40 +01:00
Mario de Frutos
7be27969fa Merge pull request #438 from CartoDB/development
Release python version 0.16.2
2018-01-30 09:58:49 +01:00
Mario de Frutos
502039796f Merge pull request #437 from CartoDB/436-Fixing_valid_types
Fixed valid Mapbox types
2018-01-30 09:42:50 +01:00
Antonio
e0b1632fa8 Fixed tests 2018-01-30 09:13:43 +01:00
Antonio
51bf6c2a43 Fixed valid Mapbox types 2018-01-29 18:39:11 +01:00
Mario de Frutos
5f9185ee6b Merge pull request #435 from CartoDB/development
Release 0.30.1 server side
2018-01-29 17:43:51 +01:00
Mario de Frutos
08e21e3999 Updated NEWS.md 2018-01-29 17:42:30 +01:00
Mario de Frutos
212cbda9a0 Merge pull request #434 from CartoDB/433-Fixing_encoding_issues
Fixing encoding issues
2018-01-29 17:40:12 +01:00
Antonio
05718ce58c Fixed KeyError Exception 2018-01-29 17:32:44 +01:00
Antonio
fed444ff6c Version bumped 2018-01-29 17:18:18 +01:00
Antonio
d1c8f8ced0 Fixing encoding issues 2018-01-29 17:09:17 +01:00
Mario de Frutos
96d2bf6218 Update NEWS.md 2018-01-18 17:27:34 +01:00
Mario de Frutos
b4dc616590 Merge pull request #432 from CartoDB/development
Release python library 0.16.1
2018-01-18 17:24:23 +01:00
Mario de Frutos
4f907053f5 Merge pull request #431 from CartoDB/430-Fixed_encoding_problems_with_mapbox_geocoding
Fixed encoding problem with Mapbox geocoding
2018-01-18 17:21:20 +01:00
Antonio
1a2785dff4 Version bumped 2018-01-18 15:21:06 +01:00
Antonio
d442fab9da Fixed encoding problem with Mapbox geocoding 2018-01-18 11:55:25 +01:00
25 changed files with 7211 additions and 47 deletions

28
NEWS.md
View File

@@ -1,3 +1,31 @@
February 2th, 2018
==================
* Version `0.16.4` of the python library
* Create a QuotaExceededException instead of using a generic one
* Version `0.30.2` of server side
* Return empty value when the quota is exceeded and don't send the exception to external loggers
to avoid noise
January 31th, 2018
==================
* Version `0.16.3` of the python library
* Fix for Mapbox geocoder to handle empty requests and empty responses
* Remove raising an exception when non parameters are passed to the HERE geocoder
* Fix for HERE geocoder with non empty requests
* Added more coverage to the google geocoder credentials parse logic
January 29th, 2018
==================
* Version `0.30.1` of server side
* Fix for Mapbox geocoding function due to the iso3166 library doesn't support UTF-8 names for the countries
* Version `0.16.2` of the python library
* Fix for Mapbox cycling profile
January 18th, 2018
==================
* Version `0.16.1` of the python library
* Fixed encoding problem with Mapbox geocoding (using the Mapbox Python library)
January 17th, 2018 January 17th, 2018
================== ==================
* Version `0.16.0` of the python library * Version `0.16.0` of the python library

View File

@@ -296,3 +296,6 @@ ALTER ROLE "<USER_ROLE>" SET search_path="$user", public, cartodb, cdb_dataservi
#### Option 2 (from builder) #### Option 2 (from builder)
See [the **Configuring Dataservices** documentation](http://cartodb.readthedocs.io/en/latest/operations/configure_data_services.html) See [the **Configuring Dataservices** documentation](http://cartodb.readthedocs.io/en/latest/operations/configure_data_services.html)
### Rate limits
See [docs](https://github.com/CartoDB/dataservices-api/blob/master/doc/rate_limits.md)

View File

@@ -14,7 +14,7 @@ Name | Type | Description | Accepted values
`destination` | `geometry(Point)` | Destination point, in 4326 projection, which defines the end location. | `destination` | `geometry(Point)` | Destination point, in 4326 projection, which defines the end location. |
`mode` | `text` | Type of transport used to calculate the routes. | `car`, `walk`, `bicycle` or `public_transport` `mode` | `text` | Type of transport used to calculate the routes. | `car`, `walk`, `bicycle` or `public_transport`
`options` | `text[]` | (Optional) Multiple options to add more capabilities to the analysis. See [Optional routing parameters](#optional-routing-parameters) for details. `options` | `text[]` | (Optional) Multiple options to add more capabilities to the analysis. See [Optional routing parameters](#optional-routing-parameters) for details.
`units` | `text` | Unit used to represent the length of the route. | `kilometers`, `miles`. By default is `kilometers` `units` | `text` | (Optional) Unit used to represent the length of the route. | `kilometers`, `miles`. By default is `kilometers`. This option is not supported by Mapbox provider
#### Returns #### Returns
@@ -22,7 +22,7 @@ Name | Type | Description | Accepted values
Name | Type | Description Name | Type | Description
--- | --- | --- --- | --- | ---
`duration` | `integer` | Duration in seconds of the calculated route. `duration` | `integer` | Duration in seconds of the calculated route.
`length` | `real` | Length in the defined unit in the `units` field. `kilometers` by default . `length` | `real` | Length in the defined unit in the `units` field. `meters` by default .
`the_geom` | `geometry(LineString)` | LineString geometry of the calculated route in the 4326 projection. `the_geom` | `geometry(LineString)` | LineString geometry of the calculated route in the 4326 projection.
#### Examples #### Examples
@@ -49,7 +49,7 @@ Name | Type | Description | Accepted values
`waypoints` | `geometry(Point)[]` | Array of ordered points, in 4326 projection, which defines the origin point, one or more locations for the route path to travel through, and the destination. The first element of the array defines the origin and the last element the destination of the route. | `waypoints` | `geometry(Point)[]` | Array of ordered points, in 4326 projection, which defines the origin point, one or more locations for the route path to travel through, and the destination. The first element of the array defines the origin and the last element the destination of the route. |
`mode` | `text` | Type of transport used to calculate the routes. | `car`, `walk`, `bicycle` or `public_transport` `mode` | `text` | Type of transport used to calculate the routes. | `car`, `walk`, `bicycle` or `public_transport`
`options` | `text[]` | (Optional) Multiple options to add more capabilities to the analysis. See [Optional routing parameters](#optional-routing-parameters) for details. `options` | `text[]` | (Optional) Multiple options to add more capabilities to the analysis. See [Optional routing parameters](#optional-routing-parameters) for details.
`units` | `text` | Unit used to represent the length of the route. | `kilometers`, `miles`. By default is `kilometers` `units` | `text` | (Optional) Unit used to represent the length of the route. | `kilometers`, `miles`. By default is `kilometers`. This option is not supported by Mapbox provider
#### Returns #### Returns
@@ -57,7 +57,7 @@ Name | Type | Description | Accepted values
Name | Type | Description Name | Type | Description
--- | --- | --- --- | --- | ---
`duration` | `integer` | Duration in seconds of the calculated route. `duration` | `integer` | Duration in seconds of the calculated route.
`length` | `real` | Length in the defined unit in the `units` field. `kilometers` by default . `length` | `real` | Length in the defined unit in the `units` field. `meters` by default .
`the_geom` | `geometry(LineString)` | LineString geometry of the calculated route in the 4326 projection. `the_geom` | `geometry(LineString)` | LineString geometry of the calculated route in the 4326 projection.
*Note*: A request to the function _cdb\_route\_with\_waypoints(waypoints geometry(Point)[], mode text, [options text[], units text])_ with only two points in the geometry array are automatically defined as origin and destination. It is equivalent to performing the following request with these two locations as parameters: _cdb\_route\_point\_to\_point(origin geometry(Point), destination geometry(Point), mode text, [options text[], units text])_. *Note*: A request to the function _cdb\_route\_with\_waypoints(waypoints geometry(Point)[], mode text, [options text[], units text])_ with only two points in the geometry array are automatically defined as origin and destination. It is equivalent to performing the following request with these two locations as parameters: _cdb\_route\_point\_to\_point(origin geometry(Point), destination geometry(Point), mode text, [options text[], units text])_.
@@ -75,10 +75,9 @@ INSERT INTO <TABLE> (duration, length, the_geom) SELECT duration, length, shape
UPDATE <TABLE> SET the_geom = (SELECT shape FROM cdb_route_with_waypoints(Array['POINT(-3.7109 40.4234)'::GEOMETRY, 'POINT(-3.7059 40.4203)'::geometry, 'POINT(-3.7046 40.4180)'::geometry]::geometry[], 'car', ARRAY['mode_type=shortest']::text[])) UPDATE <TABLE> SET the_geom = (SELECT shape FROM cdb_route_with_waypoints(Array['POINT(-3.7109 40.4234)'::GEOMETRY, 'POINT(-3.7059 40.4203)'::geometry, 'POINT(-3.7046 40.4180)'::geometry]::geometry[], 'car', ARRAY['mode_type=shortest']::text[]))
``` ```
### Optional routing parameters ### Optional routing parameters
The optional value parameters must be passed using the format: `option=value`. The optional value parameters must be passed using the format: `option=value`. Not all are available for all the routing providers
Name | Type | Description | Accepted values Name | Type | Description | Accepted values
--- | --- | --- | --- --- | --- | --- | ---

View File

@@ -0,0 +1,156 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.30.2'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_here_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.tools import LegacyServiceManager
from cartodb_services.tools import QuotaExceededException
from cartodb_services.here import HereMapsGeocoder
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
service_manager = LegacyServiceManager('geocoder', username, orgname, GD)
try:
service_manager.assert_within_limits()
geocoder = HereMapsGeocoder(service_manager.config.heremaps_app_id, service_manager.config.heremaps_app_code, service_manager.logger, service_manager.config.heremaps_service_params)
coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using here maps', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using here maps')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_google_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.tools import LegacyServiceManager, QuotaExceededException
from cartodb_services.google import GoogleMapsGeocoder
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
service_manager = LegacyServiceManager('geocoder', username, orgname, GD)
try:
service_manager.assert_within_limits(quota=False)
geocoder = GoogleMapsGeocoder(service_manager.config.google_client_id, service_manager.config.google_api_key, service_manager.logger)
coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using google maps', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using google maps')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.tools import ServiceManager, QuotaExceededException
from cartodb_services.mapzen import MapzenGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapzen_geocoder_config import MapzenGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapzenGeocoderConfigBuilder, username, orgname)
try:
service_manager.assert_within_limits()
geocoder = MapzenGeocoder(service_manager.config.mapzen_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3 = None
if country:
country_iso3 = country_to_iso3(country)
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3, search_type='address')
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using mapzen', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using mapzen')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from iso3166 import countries
from cartodb_services.tools import ServiceManager, QuotaExceededException
from cartodb_services.mapbox import MapboxGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapbox_geocoder_config import MapboxGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapboxGeocoderConfigBuilder, username, orgname, GD)
try:
service_manager.assert_within_limits()
geocoder = MapboxGeocoder(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3166 = None
if country:
country_iso3 = country_to_iso3(country)
if country_iso3:
country_iso3166 = countries.get(country_iso3).alpha2.lower()
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3166)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using mapbox', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using mapbox')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,114 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.30.1'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_here_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.tools import LegacyServiceManager
from cartodb_services.here import HereMapsGeocoder
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
service_manager = LegacyServiceManager('geocoder', username, orgname, GD)
service_manager.assert_within_limits()
try:
geocoder = HereMapsGeocoder(service_manager.config.heremaps_app_id, service_manager.config.heremaps_app_code, service_manager.logger, service_manager.config.heremaps_service_params)
coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using here maps', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using here maps')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from cartodb_services.tools import ServiceManager
from cartodb_services.mapzen import MapzenGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapzen_geocoder_config import MapzenGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapzenGeocoderConfigBuilder, username, orgname)
service_manager.assert_within_limits()
try:
geocoder = MapzenGeocoder(service_manager.config.mapzen_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3 = None
if country:
country_iso3 = country_to_iso3(country)
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3, search_type='address')
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using mapzen', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using mapzen')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from iso3166 import countries
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapbox_geocoder_config import MapboxGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapboxGeocoderConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
geocoder = MapboxGeocoder(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3166 = None
if country:
country_iso3 = country_to_iso3(country)
if country_iso3:
country_iso3166 = countries.get(country_iso3).alpha2.lower()
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3166)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using mapbox', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using mapbox')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,5 @@
comment = 'CartoDB dataservices server extension' comment = 'CartoDB dataservices server extension'
default_version = '0.30.0' default_version = '0.30.2'
requires = 'plpythonu, plproxy, postgis, cdb_geocoder' requires = 'plpythonu, plproxy, postgis, cdb_geocoder'
superuser = true superuser = true
schema = cdb_dataservices_server schema = cdb_dataservices_server

View File

@@ -0,0 +1,47 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.30.1'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from iso3166 import countries
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapbox_geocoder_config import MapboxGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapboxGeocoderConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
geocoder = MapboxGeocoder(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3166 = None
if country:
country_iso3 = country_to_iso3(country)
if country_iso3:
country_iso3166 = countries.get(country_iso3).alpha2.lower()
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3166)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using mapbox', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using mapbox')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

View File

@@ -0,0 +1,44 @@
--DO NOT MODIFY THIS FILE, IT IS GENERATED AUTOMATICALLY FROM SOURCES
-- Complain if script is sourced in psql, rather than via CREATE EXTENSION
\echo Use "ALTER EXTENSION cdb_dataservices_server UPDATE TO '0.30.0'" to load this file. \quit
-- HERE goes your code to upgrade/downgrade
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$
from iso3166 import countries
from cartodb_services.tools import ServiceManager
from cartodb_services.mapbox import MapboxGeocoder
from cartodb_services.refactor.service.mapbox_geocoder_config import MapboxGeocoderConfigBuilder
import cartodb_services
cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapboxGeocoderConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try:
geocoder = MapboxGeocoder(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3166 = None
if country:
country_iso3166 = countries.get(country).alpha2.lower()
coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province,
country=country_iso3166)
if coordinates:
service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
point = plpy.execute(plan, [coordinates[0], coordinates[1]], 1)[0]
return point['st_setsrid']
else:
service_manager.quota_service.increment_empty_service_use()
return None
except BaseException as e:
import sys
service_manager.quota_service.increment_failed_service_use()
service_manager.logger.error('Error trying to geocode street point using mapbox', sys.exc_info(), data={"username": username, "orgname": orgname})
raise Exception('Error trying to geocode street point using mapbox')
finally:
service_manager.quota_service.increment_total_service_use()
$$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;

File diff suppressed because it is too large Load Diff

View File

@@ -90,13 +90,14 @@ $$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_here_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL) CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_here_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$ RETURNS Geometry AS $$
from cartodb_services.tools import LegacyServiceManager from cartodb_services.tools import LegacyServiceManager
from cartodb_services.tools import QuotaExceededException
from cartodb_services.here import HereMapsGeocoder from cartodb_services.here import HereMapsGeocoder
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()") plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
service_manager = LegacyServiceManager('geocoder', username, orgname, GD) service_manager = LegacyServiceManager('geocoder', username, orgname, GD)
service_manager.assert_within_limits()
try: try:
service_manager.assert_within_limits()
geocoder = HereMapsGeocoder(service_manager.config.heremaps_app_id, service_manager.config.heremaps_app_code, service_manager.logger, service_manager.config.heremaps_service_params) geocoder = HereMapsGeocoder(service_manager.config.heremaps_app_id, service_manager.config.heremaps_app_code, service_manager.logger, service_manager.config.heremaps_service_params)
coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country) coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country)
if coordinates: if coordinates:
@@ -107,6 +108,9 @@ RETURNS Geometry AS $$
else: else:
service_manager.quota_service.increment_empty_service_use() service_manager.quota_service.increment_empty_service_use()
return None return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e: except BaseException as e:
import sys import sys
service_manager.quota_service.increment_failed_service_use() service_manager.quota_service.increment_failed_service_use()
@@ -118,14 +122,14 @@ $$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_google_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL) CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_google_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$ RETURNS Geometry AS $$
from cartodb_services.tools import LegacyServiceManager from cartodb_services.tools import LegacyServiceManager, QuotaExceededException
from cartodb_services.google import GoogleMapsGeocoder from cartodb_services.google import GoogleMapsGeocoder
plpy.execute("SELECT cdb_dataservices_server._get_logger_config()") plpy.execute("SELECT cdb_dataservices_server._get_logger_config()")
service_manager = LegacyServiceManager('geocoder', username, orgname, GD) service_manager = LegacyServiceManager('geocoder', username, orgname, GD)
service_manager.assert_within_limits(quota=False)
try: try:
service_manager.assert_within_limits(quota=False)
geocoder = GoogleMapsGeocoder(service_manager.config.google_client_id, service_manager.config.google_api_key, service_manager.logger) geocoder = GoogleMapsGeocoder(service_manager.config.google_client_id, service_manager.config.google_api_key, service_manager.logger)
coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country) coordinates = geocoder.geocode(searchtext=searchtext, city=city, state=state_province, country=country)
if coordinates: if coordinates:
@@ -136,6 +140,9 @@ RETURNS Geometry AS $$
else: else:
service_manager.quota_service.increment_empty_service_use() service_manager.quota_service.increment_empty_service_use()
return None return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e: except BaseException as e:
import sys import sys
service_manager.quota_service.increment_failed_service_use() service_manager.quota_service.increment_failed_service_use()
@@ -147,7 +154,7 @@ $$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL) CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapzen_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$ RETURNS Geometry AS $$
from cartodb_services.tools import ServiceManager from cartodb_services.tools import ServiceManager, QuotaExceededException
from cartodb_services.mapzen import MapzenGeocoder from cartodb_services.mapzen import MapzenGeocoder
from cartodb_services.tools.country import country_to_iso3 from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapzen_geocoder_config import MapzenGeocoderConfigBuilder from cartodb_services.refactor.service.mapzen_geocoder_config import MapzenGeocoderConfigBuilder
@@ -156,9 +163,9 @@ RETURNS Geometry AS $$
cartodb_services.init(plpy, GD) cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapzenGeocoderConfigBuilder, username, orgname) service_manager = ServiceManager('geocoder', MapzenGeocoderConfigBuilder, username, orgname)
service_manager.assert_within_limits()
try: try:
service_manager.assert_within_limits()
geocoder = MapzenGeocoder(service_manager.config.mapzen_api_key, service_manager.logger, service_manager.config.service_params) geocoder = MapzenGeocoder(service_manager.config.mapzen_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3 = None country_iso3 = None
if country: if country:
@@ -174,6 +181,9 @@ RETURNS Geometry AS $$
else: else:
service_manager.quota_service.increment_empty_service_use() service_manager.quota_service.increment_empty_service_use()
return None return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e: except BaseException as e:
import sys import sys
service_manager.quota_service.increment_failed_service_use() service_manager.quota_service.increment_failed_service_use()
@@ -186,26 +196,29 @@ $$ LANGUAGE plpythonu STABLE PARALLEL RESTRICTED;
CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL) CREATE OR REPLACE FUNCTION cdb_dataservices_server._cdb_mapbox_geocode_street_point(username TEXT, orgname TEXT, searchtext TEXT, city TEXT DEFAULT NULL, state_province TEXT DEFAULT NULL, country TEXT DEFAULT NULL)
RETURNS Geometry AS $$ RETURNS Geometry AS $$
from iso3166 import countries from iso3166 import countries
from cartodb_services.tools import ServiceManager from cartodb_services.tools import ServiceManager, QuotaExceededException
from cartodb_services.mapbox import MapboxGeocoder from cartodb_services.mapbox import MapboxGeocoder
from cartodb_services.tools.country import country_to_iso3
from cartodb_services.refactor.service.mapbox_geocoder_config import MapboxGeocoderConfigBuilder from cartodb_services.refactor.service.mapbox_geocoder_config import MapboxGeocoderConfigBuilder
import cartodb_services import cartodb_services
cartodb_services.init(plpy, GD) cartodb_services.init(plpy, GD)
service_manager = ServiceManager('geocoder', MapboxGeocoderConfigBuilder, username, orgname, GD) service_manager = ServiceManager('geocoder', MapboxGeocoderConfigBuilder, username, orgname, GD)
service_manager.assert_within_limits()
try: try:
service_manager.assert_within_limits()
geocoder = MapboxGeocoder(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params) geocoder = MapboxGeocoder(service_manager.config.mapbox_api_key, service_manager.logger, service_manager.config.service_params)
country_iso3166 = None country_iso3166 = None
if country: if country:
country_iso3166 = countries.get(country).alpha2.lower() country_iso3 = country_to_iso3(country)
if country_iso3:
country_iso3166 = countries.get(country_iso3).alpha2.lower()
coordinates = geocoder.geocode(searchtext=searchtext, city=city, coordinates = geocoder.geocode(searchtext=searchtext, city=city,
state_province=state_province, state_province=state_province,
country=country_iso3166) country=country_iso3166)
if coordinates: if coordinates:
service_manager.quota_service.increment_success_service_use() service_manager.quota_service.increment_success_service_use()
plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"]) plan = plpy.prepare("SELECT ST_SetSRID(ST_MakePoint($1, $2), 4326); ", ["double precision", "double precision"])
@@ -214,6 +227,9 @@ RETURNS Geometry AS $$
else: else:
service_manager.quota_service.increment_empty_service_use() service_manager.quota_service.increment_empty_service_use()
return None return None
except QuotaExceededException as qe:
service_manager.quota_service.increment_failed_service_use()
return None
except BaseException as e: except BaseException as e:
import sys import sys
service_manager.quota_service.increment_failed_service_use() service_manager.quota_service.increment_failed_service_use()

View File

@@ -67,10 +67,10 @@ class HereMapsGeocoder(Traceable):
def geocode(self, **kwargs): def geocode(self, **kwargs):
params = {} params = {}
for key, value in kwargs.iteritems(): for key, value in kwargs.iteritems():
if value: if value and value.strip():
params[key] = value params[key] = value
if not params: if not params:
raise NoGeocodingParams() return []
return self._execute_geocode(params) return self._execute_geocode(params)
def _execute_geocode(self, params): def _execute_geocode(self, params):

View File

@@ -39,7 +39,7 @@ class MapboxGeocoder(Traceable):
def _parse_geocoder_response(self, response): def _parse_geocoder_response(self, response):
json_response = json.loads(response) json_response = json.loads(response)
if json_response: if json_response and json_response[ENTRY_FEATURES]:
feature = json_response[ENTRY_FEATURES][0] feature = json_response[ENTRY_FEATURES][0]
return self._extract_lng_lat_from_feature(feature) return self._extract_lng_lat_from_feature(feature)
@@ -60,16 +60,19 @@ class MapboxGeocoder(Traceable):
@qps_retry(qps=10) @qps_retry(qps=10)
def geocode(self, searchtext, city=None, state_province=None, def geocode(self, searchtext, city=None, state_province=None,
country=None): country=None):
address = [searchtext] if searchtext and searchtext.strip():
if city: address = [searchtext]
address.append(city) if city:
if state_province: address.append(city)
address.append(state_province) if state_province:
address.append(state_province)
else:
return []
country = [country] if country else None country = [country] if country else None
try: try:
response = self._geocoder.forward(address=', '.join(address), response = self._geocoder.forward(address=', '.join(address).decode('utf-8'),
country=country, country=country,
limit=1) limit=1)

View File

@@ -5,4 +5,5 @@ MAPBOX_ISOLINES_APIKEY_ROUNDROBIN = 'mapbox_isolines_apikey_roundrobin'
TRANSPORT_MODE_TO_MAPBOX = { TRANSPORT_MODE_TO_MAPBOX = {
'car': 'driving', 'car': 'driving',
'walk': 'walking', 'walk': 'walking',
'bicycle': 'cycling',
} }

View File

@@ -3,5 +3,7 @@ from coordinates import Coordinate
from polyline import PolyLine from polyline import PolyLine
from log import Logger, LoggerConfig from log import Logger, LoggerConfig
from rate_limiter import RateLimiter from rate_limiter import RateLimiter
from service_manager import ServiceManager, RateLimitExceeded from service_manager import ServiceManager
from legacy_service_manager import LegacyServiceManager from legacy_service_manager import LegacyServiceManager
from exceptions import QuotaExceededException, RateLimitExceeded
from country import country_to_iso3

View File

@@ -1,6 +1,5 @@
import json import json
class TimeoutException(Exception): class TimeoutException(Exception):
def __str__(self): def __str__(self):
return repr('Timeout requesting to server') return repr('Timeout requesting to server')
@@ -29,3 +28,11 @@ class WrongParams(Exception):
class MalformedResult(Exception): class MalformedResult(Exception):
def __str__(self): def __str__(self):
return repr('Result structure is malformed') return repr('Result structure is malformed')
class RateLimitExceeded(Exception):
def __str__(self):
return repr('Rate limit exceeded')
class QuotaExceededException(Exception):
def __str__(self):
return repr('You have reached the limit of your quota')

View File

@@ -1,16 +1,12 @@
from cartodb_services.metrics import QuotaService from cartodb_services.metrics import QuotaService
from cartodb_services.tools import Logger from cartodb_services.tools.log import Logger
from cartodb_services.tools import RateLimiter from cartodb_services.tools.rate_limiter import RateLimiter
from cartodb_services.tools.exceptions import QuotaExceededException, RateLimitExceeded
from cartodb_services.refactor.tools.logger import LoggerConfigBuilder from cartodb_services.refactor.tools.logger import LoggerConfigBuilder
from cartodb_services.refactor.backend.redis_metrics_connection import RedisMetricsConnectionFactory from cartodb_services.refactor.backend.redis_metrics_connection import RedisMetricsConnectionFactory
from cartodb_services.config import ServiceConfiguration, RateLimitsConfigBuilder from cartodb_services.config import ServiceConfiguration, RateLimitsConfigBuilder
class RateLimitExceeded(Exception):
def __str__(self):
return repr('Rate limit exceeded')
class ServiceManagerBase: class ServiceManagerBase:
""" """
A Service manager collects the configuration needed to use a service, A Service manager collects the configuration needed to use a service,
@@ -37,7 +33,7 @@ class ServiceManagerBase:
if rate and not self.rate_limiter.check(): if rate and not self.rate_limiter.check():
raise RateLimitExceeded() raise RateLimitExceeded()
if quota and not self.quota_service.check_user_quota(): if quota and not self.quota_service.check_user_quota():
raise Exception('You have reached the limit of your quota') raise QuotaExceededException()
@property @property
def config(self): def config(self):

View File

@@ -10,7 +10,7 @@ from setuptools import setup, find_packages
setup( setup(
name='cartodb_services', name='cartodb_services',
version='0.16.0', version='0.16.4',
description='CartoDB Services API Python Library', description='CartoDB Services API Python Library',

View File

@@ -18,10 +18,10 @@ class GoogleMapsClientFactoryTestCase(unittest.TestCase):
GoogleMapsClientFactory.clients = {} GoogleMapsClientFactory.clients = {}
def test_consecutive_calls_with_same_params_return_same_client(self): def test_consecutive_calls_with_same_params_return_same_client(self):
id = 'any_id' client_id = 'any_id'
key = base64.b64encode('any_key') key = base64.b64encode('any_key')
client1 = GoogleMapsClientFactory.get(id, key) client1 = GoogleMapsClientFactory.get(client_id, key)
client2 = GoogleMapsClientFactory.get(id, key) client2 = GoogleMapsClientFactory.get(client_id, key)
self.assertEqual(client1, client2) self.assertEqual(client1, client2)
def test_consecutive_calls_with_different_key_return_different_clients(self): def test_consecutive_calls_with_different_key_return_different_clients(self):
@@ -29,11 +29,11 @@ class GoogleMapsClientFactoryTestCase(unittest.TestCase):
This requirement is important for security reasons as well as not to This requirement is important for security reasons as well as not to
cache a wrong key accidentally. cache a wrong key accidentally.
""" """
id = 'any_id' client_id = 'any_id'
key1 = base64.b64encode('any_key') key1 = base64.b64encode('any_key')
key2 = base64.b64encode('another_key') key2 = base64.b64encode('another_key')
client1 = GoogleMapsClientFactory.get(id, key1) client1 = GoogleMapsClientFactory.get(client_id, key1)
client2 = GoogleMapsClientFactory.get(id, key2) client2 = GoogleMapsClientFactory.get(client_id, key2)
self.assertNotEqual(client1, client2) self.assertNotEqual(client1, client2)
def test_consecutive_calls_with_different_ids_return_different_clients(self): def test_consecutive_calls_with_different_ids_return_different_clients(self):
@@ -59,3 +59,11 @@ class GoogleMapsClientFactoryTestCase(unittest.TestCase):
def test_credentials_with_underscores_can_be_valid(self): def test_credentials_with_underscores_can_be_valid(self):
client = GoogleMapsClientFactory.get('yet_another_dummy_client_id', 'Ola_k_ase___') client = GoogleMapsClientFactory.get('yet_another_dummy_client_id', 'Ola_k_ase___')
self.assertIsInstance(client, googlemaps.Client) self.assertIsInstance(client, googlemaps.Client)
def test_invalid_credentials(self):
with self.assertRaises(InvalidGoogleCredentials):
GoogleMapsClientFactory.get('dummy_client_id', 'lalala')
def test_credentials_with_channel(self):
client = GoogleMapsClientFactory.get('yet_another_dummy_client_id', 'Ola_k_ase___', 'channel')
self.assertIsInstance(client, googlemaps.Client)

View File

@@ -118,3 +118,18 @@ class GoogleGeocoderTestCase(unittest.TestCase):
searchtext='Calle Eloy Gonzalo 27', searchtext='Calle Eloy Gonzalo 27',
city='Madrid', city='Madrid',
country='España') country='España')
def test_client_data_extraction(self, req_mock):
client_id, channel = self.geocoder.parse_client_id('dummy_client_id')
self.assertEqual(client_id, 'dummy_client_id')
self.assertEqual(channel, None)
def test_client_data_extraction_with_client_parameter(self, req_mock):
client_id, channel = self.geocoder.parse_client_id('client=gme-test')
self.assertEqual(client_id, 'gme-test')
self.assertEqual(channel, None)
def test_client_data_extraction_with_client_and_channel_parameter(self, req_mock):
client_id, channel = self.geocoder.parse_client_id('client=gme-test&channel=testchannel')
self.assertEqual(client_id, 'gme-test')
self.assertEqual(channel, 'testchannel')

View File

@@ -128,8 +128,14 @@ class HereMapsGeocoderTestCase(unittest.TestCase):
def test_geocode_address_with_no_params(self, req_mock): def test_geocode_address_with_no_params(self, req_mock):
req_mock.register_uri('GET', HereMapsGeocoder.PRODUCTION_GEOCODE_JSON_URL, req_mock.register_uri('GET', HereMapsGeocoder.PRODUCTION_GEOCODE_JSON_URL,
text=self.GOOD_RESPONSE) text=self.GOOD_RESPONSE)
with self.assertRaises(NoGeocodingParams): result = self.geocoder.geocode()
self.geocoder.geocode() self.assertEqual(result, [])
def test_geocode_address_with_non_empty_string_params(self, req_mock):
req_mock.register_uri('GET', HereMapsGeocoder.PRODUCTION_GEOCODE_JSON_URL,
text=self.GOOD_RESPONSE)
result = self.geocoder.geocode(searchtext=" ", city=None, state=" ", country=" ")
self.assertEqual(result, [])
def test_geocode_address_empty_response(self, req_mock): def test_geocode_address_empty_response(self, req_mock):
req_mock.register_uri('GET', HereMapsGeocoder.PRODUCTION_GEOCODE_JSON_URL, req_mock.register_uri('GET', HereMapsGeocoder.PRODUCTION_GEOCODE_JSON_URL,

View File

@@ -22,8 +22,8 @@ class MapboxGeocoderTestCase(unittest.TestCase):
def test_valid_request(self): def test_valid_request(self):
place = self.geocoder.geocode(VALID_ADDRESS) place = self.geocoder.geocode(VALID_ADDRESS)
self.assertEqual(place[0], WELL_KNOWN_LONGITUDE) self.assertEqual('%.3f' % place[0], '%.3f' % WELL_KNOWN_LONGITUDE)
self.assertEqual(place[1], WELL_KNOWN_LATITUDE) self.assertEqual('%.3f' % place[1], '%.3f' % WELL_KNOWN_LATITUDE)
def test_valid_request_namedplace(self): def test_valid_request_namedplace(self):
place = self.geocoder.geocode(searchtext='Barcelona') place = self.geocoder.geocode(searchtext='Barcelona')
@@ -34,3 +34,18 @@ class MapboxGeocoderTestCase(unittest.TestCase):
place = self.geocoder.geocode(searchtext='New York', country='us') place = self.geocoder.geocode(searchtext='New York', country='us')
assert place assert place
def test_empty_request(self):
place = self.geocoder.geocode(searchtext='', country=None, city=None, state_province=None)
assert place == []
def test_empty_search_text_request(self):
place = self.geocoder.geocode(searchtext=' ', country='us', city=None, state_province="")
assert place == []
def test_unknown_place_request(self):
place = self.geocoder.geocode(searchtext='[unknown]', country='ch', state_province=None, city=None)
assert place == []