Skip to content

Commit

Permalink
Merge 7b3c20d into d86c2cd
Browse files Browse the repository at this point in the history
  • Loading branch information
makella committed Oct 12, 2019
2 parents d86c2cd + 7b3c20d commit d2e6b2b
Show file tree
Hide file tree
Showing 33 changed files with 17,357 additions and 4,251 deletions.
34 changes: 21 additions & 13 deletions cartoframes/auth/credentials.py
@@ -1,4 +1,4 @@
"""Credentials management for cartoframes usage."""
"""Credentials management for CARTOframes usage."""

import os
import sys
Expand Down Expand Up @@ -28,16 +28,18 @@ class Credentials(object):
"""Credentials class for managing and storing user CARTO credentials. The
arguments are listed in order of precedence: :obj:`Credentials` instances
are first, `key` and `base_url`/`username` are taken next, and
`config_file` (if given) is taken last. If no arguments are passed, then
there will be an attempt to retrieve credentials from a previously saved
session. One of the above scenarios needs to be met to successfully
`config_file` (if given) is taken last. The config file is `cartocreds.json`
by default. If no arguments are passed, then there will be an attempt to
retrieve credentials from a previously saved session.
One of the above scenarios needs to be met to successfully
instantiate a :obj:`Credentials` object.
Args:
api_key (str, optional): API key of user's CARTO account
api_key (str, optional): API key of user's CARTO account. If the dataset is
public, it can be set to 'default_public'.
username (str, optional): Username of CARTO account
base_url (str, optional): Base URL used for API calls. This is usually
of the form `https://eschbacher.carto.com/` for user `eschbacher`.
of the form `https://johnsmith.carto.com/` for user `johnsmith`.
On premises installations (and others) have a different URL
pattern.
session (requests.Session, optional): requests session. See `requests
Expand All @@ -47,10 +49,12 @@ class Credentials(object):
Example:
Setting basic credentials:
.. code::
from cartoframes.auth import Credentials
credentials = Credentials(username='eschbacher', api_key='abcdefg')
credentials = Credentials(username='johnsmith', api_key='abcdefg')
"""

Expand Down Expand Up @@ -145,7 +149,7 @@ def save(self, config_file=None):
"""Saves current user credentials to user directory.
Args:
config_loc (str, optional): Location where credentials are to be
config_file (str, optional): Location where credentials are to be
stored. If no argument is provided, it will be send to the
default location.
Expand All @@ -154,13 +158,13 @@ def save(self, config_file=None):
.. code::
from cartoframes.auth import Credentials
credentials = Credentials(username='eschbacher', api_key='abcdefg')
credentials = Credentials(username='johnsmith', api_key='abcdefg')
credentials.save() # save to default location
.. code::
from cartoframes.auth import Credentials
credentials = Credentials(username='eschbacher', api_key='abcdefg')
credentials = Credentials(username='johnsmith', api_key='abcdefg')
credentials.save('path/to/credentials/file')
"""

Expand All @@ -177,7 +181,8 @@ def save(self, config_file=None):
@classmethod
def delete(self, config_file=None):
"""Deletes the credentials file specified in `config_file`. If no
file is specified, it deletes the default user credential file.
file is specified, it deletes the default user credential file
(`cartocreds.json`)
Args:
Expand All @@ -191,19 +196,22 @@ def delete(self, config_file=None):
>>> credentials = Credentials.from_file()
>>> print(credentials)
Credentials(username='eschbacher', api_key='abcdefg',
base_url='https://eschbacher.carto.com/')
Credentials(username='johnsmith', api_key='abcdefg',
base_url='https://johnsmith.carto.com/')
"""

path_to_remove = config_file or _DEFAULT_PATH

try:
os.remove(path_to_remove)
warnings.warn('Credentials at {} successfully removed.'.format(path_to_remove))
except OSError:
warnings.warn('No credential file found at {}.'.format(path_to_remove))

def get_do_token(self):
"""Returns the Data Observatory v2 token"""

do_token_manager = DoTokenManager(self.get_api_key_auth_client())
token = do_token_manager.get()
if not token:
Expand Down
22 changes: 14 additions & 8 deletions cartoframes/auth/defaults.py
Expand Up @@ -19,7 +19,7 @@ def set_default_credentials(
instance can be used in place of a `username | base_url`/`api_key` combination.
base_url (str, optional): Base URL of CARTO user account. Cloud-based accounts
should use the form ``https://{username}.carto.com`` (e.g.,
https://eschbacher.carto.com for user ``eschbacher``) whether on
https://johnsmith.carto.com for user ``johnsmith``) whether on
a personal or multi-user account. On-premises installation users
should ask their admin.
api_key (str, optional): CARTO API key.
Expand All @@ -37,12 +37,12 @@ def set_default_credentials(
from cartoframes.auth import set_default_credentials
set_default_credentials(
username='your_user_name',
username='johnsmith',
api_key='your api key'
)
# or
set_default_credentials(
'your_user_name',
'johnsmith',
'your api key'
)
Expand All @@ -52,20 +52,20 @@ def set_default_credentials(
.. code::
from cartoframes.auth import set_default_credentials
set_default_credentials('your_user_name')
set_default_credentials('johnsmith')
From a pair base_url, api_key.
.. code::
from cartoframes.auth import set_default_credentials
set_default_credentials(
base_url='https://your_user_name.carto.com',
base_url='https://johnsmith.carto.com',
api_key='your api key'
)
# or
set_default_credentials(
'https://your_user_name.carto.com',
'https://johnsmith.carto.com',
'your api key'
)
Expand All @@ -75,15 +75,15 @@ def set_default_credentials(
.. code::
from cartoframes.auth import set_default_credentials
set_default_credentials('https://your_user_name.carto.com')
set_default_credentials('https://johnsmith.carto.com')
From a :py:class:`Credentials <cartoframes.auth.Credentials>` class.
.. code::
from cartoframes.auth import Credentials, set_default_credentials
credentials = Credentials(
base_url='https://your_user_name.carto.com',
base_url='https://johnsmith.carto.com',
api_key='your api key'
)
set_default_credentials(credentials)
Expand Down Expand Up @@ -115,6 +115,12 @@ def set_default_credentials(


def get_default_credentials():
"""get_default_credentials
Returns:
:obj:`Credentials`: The credentials that have been set by default.
"""
return _default_credentials


Expand Down
1 change: 1 addition & 0 deletions docs/developer-center/guides/01-Introduction.md
@@ -0,0 +1 @@
## Introduction
193 changes: 193 additions & 0 deletions docs/developer-center/guides/02-Quickstart.md
@@ -0,0 +1,193 @@
## Quickstart

### About this Guide

This guide walks through the process of authenticating CARTOframes to create an interactive visualization with a shareable link. The full notebook example can be found in the [01_basic_usage](https://github.com/CartoDB/cartoframes/blob/develop/examples/01_quickstart/01_basic_usage.ipynb) notebook.

![Final visualization](../../img/guides/quickstart/quickstart-final.gif)

### Install CARTOframes

If you don't have CARTOframes installed, check out the installation steps [here](../../guides/03-Install-CARTOframes-in-your-Notebooks.md) to get started.

### Authentication

If you have a CARTO account that you want to use with CARTOframes, you need to authenticate it by passing in your CARTO credentials. You will need your username (`base_url`) and an API key (`api_key`), which can be found at http://your_user_name.carto.com/your_apps.

If you don't have a CARTO account but want to try out CARTOframes, you only need the `cartoframes` library. To learn more, take a look at the [Data Workflow](LINK) examples to visualize data from either a Dataframe or a GeoJSON.

When using a CARTO account, the elements you need to authenticate are under the `cartoframes.auth` namespace. For this guide, we'll use a public dataset from the `cartoframes` account called [`spend_data`](https://cartoframes.carto.com/tables/spend_data/public/map) that contains information about customer spending activities in the city of Barcelona .

```py
from cartoframes.auth import set_default_credentials
from cartoframes.viz import Map, Layer

set_default_credentials(
username='cartoframes',
api_key='default_public'
)

Map(Layer('spend_data'))
```

![Visualize the 'spend_data' dataset](../../img/guides/quickstart/quickstart-1.png)

### Change the viewport and basemap

By default, the map's center and zoom is set to encompass the entire dataset and visualized on CARTO's Positron basemap. For this map, let's modify these settings to use CARTO's Dark Matter basemap and adjust the viewport to better suite our area of interest:

```py
from cartoframes.viz import Map, Layer, basemaps

Map(
Layer('spend_data'),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter,
show_info=True
)
```

### Apply a SQL Query to the Layer

Next, let's filter the data to only show the features where the purchase amount is between 150€ and 200€ using a simple SQL Query:

```py
Map(
Layer('SELECT * FROM spend_data WHERE amount > 150 AND amount < 200'),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter
)
```

![Apply a simple SQL Query](../../img/guides/quickstart/quickstart-2.png)

## Styles, Legends and Popups

There are two ways to change a layer's style and add legends, popups and widgets: manually (provides greater customization) or with visualization helpers.

First, let's take a look at how to do this manually and in the next section, we will use a visualization helper.

### Change the Style

To manually overwrite the default color and size of features, you can use the [CARTO VL String API](https://carto.com/developers/carto-vl/guides/style-with-expressions/). This API is very powerful because it allows you to style your visualizations with a few lines of code.

The style can be set directly as the **second** parameter of a Layer.

```py
Map(
Layer(
'SELECT * FROM spend_data WHERE amount > 150 AND amount < 200',
'color: ramp($category, bold)'
),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter
)
```

![Style by $category](../../img/guides/quickstart/quickstart-3.png)

### Add a Legend

In this case, the **third** parameter of a Layer is the Legend:

```py
from cartoframes.viz import Legend

Map(
Layer(
'SELECT * FROM spend_data WHERE amount > 150 AND amount < 200',
'color: ramp($category, bold)',
legend=Legend(
'color-bins',
title= 'Categories'
)
),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter
)
```

![Add a legend for the styled category](../../img/guides/quickstart/quickstart-4.png)

### Add a Popup

Now, let's add the Popup settings in the **fourth** parameter:

```py
Map(
Layer(
'SELECT * FROM spend_data WHERE amount > 150 AND amount < 200',
'color: ramp($category, bold)',
legend=Legend(
'color-bins',
title= 'Categories'
),
popup=Popup({
'hover': {
'title': 'Hour',
'value': '$hour'
}
})
),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter
)
```

![Show popups when interacting with the features](../../img/guides/quickstart/quickstart-5.png)

### Add a Widget

Next, let's add a Widget in the **fifth** parameter:

```py
from cartoframes.viz.widgets import histogram_widget

Map(
Layer(
'SELECT * FROM spend_data WHERE amount > 150 AND amount < 200',
'color: ramp(top($category,10), bold)',
legend=Legend(
'color-bins',
title= 'Spending Categories'
),
popup=Popup({
'hover': {
'title': 'Hour',
'value': '$hour'
}
}),
widgets=[
histogram_widget(
'amount',
title='Amount Spent (€)',
description='Select a range of values to filter'
)
]
),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter
)
```

## Use a Visualization Helper

CARTOframes has a set of built-in [Helper Methods]({{ site.url }}/developers/cartoframes/guides/helper-methods-part-1/) that can be used to create visualizations with default style, legends and popups, all together!.

```py
from cartoframes.viz.helpers import color_category_layer

Map(
color_category_layer(
'SELECT * FROM spend_data WHERE amount > 150 AND amount < 200',
'category',
'Spending in Barcelona',
description='Categories',
widget=True
),
viewport={'zoom': 12, 'lat': 41.38, 'lng': 2.17},
basemap=basemaps.darkmatter
)
```

![Final visualization](../../img/guides/quickstart/quickstart-final.gif)

0 comments on commit d2e6b2b

Please sign in to comment.