Skip to content

Commit

Permalink
Merge bad51a3 into 0aee971
Browse files Browse the repository at this point in the history
  • Loading branch information
michellemho committed Oct 31, 2017
2 parents 0aee971 + bad51a3 commit 7944f3c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 25 deletions.
44 changes: 24 additions & 20 deletions cartoframes/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def write(self, df, table_name, temp_dir=CACHE_DIR,
:obj:`BatchJobStatus` or None: If `lnglat` flag is set and the
DataFrame has more than 100,000 rows, a :obj:`BatchJobStatus`
instance is returned. Otherwise, None.
"""
""" # noqa
if not os.path.exists(temp_dir):
self._debug_print(temp_dir='creating directory at ' + temp_dir)
os.makedirs(temp_dir)
Expand Down Expand Up @@ -746,13 +746,13 @@ def map(self, layers=None, interactive=True,
if not layer.is_basemap:
# get schema of style columns
resp = self.sql_client.send('''
SELECT {cols}
FROM ({query}) AS _wrap
LIMIT 0
'''.format(cols=','.join(layer.style_cols),
comma=',' if layer.style_cols else '',
query=layer.query),
**DEFAULT_SQL_ARGS)
SELECT {cols}
FROM ({query}) AS _wrap
LIMIT 0
'''.format(cols=','.join(layer.style_cols),
comma=',' if layer.style_cols else '',
query=layer.orig_query),
**DEFAULT_SQL_ARGS)
self._debug_print(layer_fields=resp)
for k, v in dict_items(resp['fields']):
layer.style_cols[k] = v['type']
Expand Down Expand Up @@ -852,17 +852,21 @@ def safe_quotes(text, escape_single_quotes=False):

if time_layer:
# get turbo-carto processed cartocss
params.update(dict(callback='cartoframes'))
resp = requests.get(
os.path.join(self.creds.base_url(),
'api/v1/map/named', map_name, 'jsonp'),
params=params,
resp = self._auth_send(
'api/v1/map/named/{}'.format(map_name),
'POST',
data=params['config'],
headers={'Content-Type': 'application/json'})

# replace previous cartocss with turbo-carto processed version
layer.cartocss = json.loads(
resp.text.split('&& cartoframes(')[1]
.strip(');'))['metadata']['layers'][1]['meta']['cartocss']
# check if errors in cartocss (already turbo-carto processed)
if 'errors' not in resp:
# replace previous cartocss with turbo-carto processed
# version
layer.cartocss = (resp['metadata']
['layers']
[1]
['meta']
['cartocss'])
config.update({
'order': 1,
'options': {
Expand Down Expand Up @@ -936,12 +940,12 @@ def _geom_type(self, layer):
WHERE the_geom IS NOT NULL
GROUP BY 1
ORDER BY 2 DESC
'''.format(query=layer.query),
'''.format(query=layer.orig_query),
**DEFAULT_SQL_ARGS)
if len(resp['rows']) > 1:
warn('There are multiple geometry types in {query}: '
'{geoms}. Styling by `{common_geom}`, the most common'.format(
query=layer.query,
query=layer.orig_query,
geoms=','.join(g['geom_type'] for g in resp['rows']),
common_geom=resp['rows'][0]['geom_type']))
return resp['rows'][0]['geom_type']
Expand Down Expand Up @@ -1124,7 +1128,7 @@ def _get_bounds(self, layers):
extent_query = ('SELECT ST_EXTENT(the_geom) AS the_geom '
'FROM ({query}) AS t{idx}\n')
union_query = 'UNION ALL\n'.join(
[extent_query.format(query=layer.query, idx=idx)
[extent_query.format(query=layer.orig_query, idx=idx)
for idx, layer in enumerate(layers)
if not layer.is_basemap])

Expand Down
11 changes: 6 additions & 5 deletions cartoframes/layer.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,6 @@ class QueryLayer(AbstractLayer):
Defaults to 30.
- trails (`int`, optional): Number of trails after the incidence of
a point. Defaults to 2.
color (dict or str, optional): Color style to apply to map. For
example, this can be used to change the color of all geometries
in this layer, or to create a graduated color or choropleth map.
Expand Down Expand Up @@ -234,11 +233,12 @@ class QueryLayer(AbstractLayer):
tooltip (tuple, optional): **Not yet implemented.**
legend: **Not yet implemented.**
"""
""" # noqa
def __init__(self, query, time=None, color=None, size=None,
tooltip=None, legend=None):

self.query = query
self.orig_query = query
# style_cols and geom_type are updated right before layer is `_setup`
# style columns as keys, data types as values
self.style_cols = dict()
Expand Down Expand Up @@ -372,7 +372,8 @@ def _setup(self, layers, layer_idx):
if self.geom_type != 'point':
raise ValueError('Cannot do time-based maps with data in '
'`{query}` since this table does not contain '
'point geometries'.format(query=self.query))
'point geometries'.format(
query=self.orig_query))
elif self.style_cols[self.time['column']] not in (
'number', 'date', ):
raise ValueError('Cannot create an animated map from column '
Expand Down Expand Up @@ -404,7 +405,7 @@ def _setup(self, layers, layer_idx):
' ) AS _wrap',
') AS __wrap',
'WHERE __wrap.{col} = orig.{col}',
]]).format(col=self.color, query=self.query)
]]).format(col=self.color, query=self.orig_query)
agg_func = '\'CDB_Math_Mode(cf_value_{})\''.format(self.color)
self.scheme = {
'bins': ','.join(str(i) for i in range(1, 11)),
Expand All @@ -417,7 +418,7 @@ def _setup(self, layers, layer_idx):
self.query = ' '.join([
'SELECT *, {col} as value',
'FROM ({query}) as _wrap'
]).format(col=self.color, query=self.query)
]).format(col=self.color, query=self.orig_query)
agg_func = '\'avg({})\''.format(self.color)
else:
agg_func = "'{method}(cartodb_id)'".format(
Expand Down

0 comments on commit 7944f3c

Please sign in to comment.