carto

CARTO Python client

https://github.com/cartodb/carto-python

Science Score: 10.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    1 of 35 committers (2.9%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (15.3%) to scientific vocabulary
Last synced: 11 months ago · JSON representation

Repository

CARTO Python client

Basic Info
  • Host: GitHub
  • Owner: CartoDB
  • License: bsd-3-clause
  • Language: Python
  • Default Branch: master
  • Homepage: https://carto.com
  • Size: 1.43 MB
Statistics
  • Stars: 154
  • Watchers: 91
  • Forks: 62
  • Open Issues: 20
  • Releases: 0
Created over 15 years ago · Last pushed almost 5 years ago
Metadata Files
Readme Contributing License

README.md

carto-python

Documentation Status

Python SDK for Carto's APIs:

carto-python is a full, backwards incompatible rewrite of the deprecated cartodb-python SDK. Since the initial rewrite, carto-python has been loaded with a lot of new features, not present in old cartodb-python.

Installation

You can install carto-python by cloning this repository or by using Pip:

pip install carto

If you want to use the development version, you can install directly from github:

pip install -e git+git://github.com/CartoDB/carto-python.git#egg=carto

If using, the development version, you might want to install Carto's dependencies as well:

pip install -r requirements.txt

Test Suite

Create a secret.py from secret.py.example, fill the variables, cd into the repo folder, create and enable virtualenv, install pytest and run tests:

cd carto-python virtualenv env source env/bin/activate pip install -e . pip install -r test_requirements.txt pip install pytest py.test tests

Authentication

Before making API calls, we need to define how those calls are going to be authenticated. Currently, we support two different authentication methods: unauthenticated and API key based. Therefore, we first need to create an authentication client that will be used when instantiating the Python classes that deal with API requests.

For unauthenticated requests, we need to create a NoAuthClient object:

```python from carto.auth import NoAuthClient

USERNAME="type here your username" USRBASEURL = "https://{user}.carto.com/".format(user=USERNAME) authclient = NoAuthClient(baseurl=USRBASEURL) ```

For API key authenticated requests, we need to create an APIKeyAuthClient instance:

```python from carto.auth import APIKeyAuthClient

USERNAME="type here your username" USRBASEURL = "https://{user}.carto.com/".format(user=USERNAME) authclient = APIKeyAuthClient(apikey="myapikey", baseurl=USRBASE_URL) ```

API key is mandatory for all API requests except for sending SQL queries to public datasets.

The base_url parameter must include the user and or the organization

BASE_URL = "https://{organization}.carto.com/user/{user}/". \ format(organization=ORGANIZATION, user=USERNAME) USR_BASE_URL = "https://{user}.carto.com/".format(user=USERNAME)

Additionally, see test_auth.py for supported formats for the base_url parameter.

For a detailed description of the rest of parameters both constructors accept, please take a look at the documentation of the source code.

SQL API

Making requests to the SQL API is pretty straightforward:

```python from carto.sql import SQLClient

sql = SQLClient(auth_client)

try: data = sql.send('select * from mytable') except CartoException as e: print("some error ocurred", e)

print data['rows'] ```

Please refer to the source code documentation to find out about the rest of the parameters accepted by the constructor and the send method. In particular, the send method allows you to control the format of the results.

Batch SQL requests

For long lasting SQL queries you can use the batch SQL API.

```python from carto.sql import BatchSQLClient

LISTOFSQL_QUERIES = []

batchSQLClient = BatchSQLClient(authclient) createJob = batchSQLClient.create(LISTOFSQLQUERIES)

print(createJob['job_id']) ```

The BatchSQLClient is asynchronous, but it offers methods to check the status of a job, update it or cancel it:

```python

check the status of a job after it has been created and you have the job_id

readJob = batchSQLClient.read(job_id)

update the query of a batch job

updateJob = batchSQLClient.update(jobid, NEWQUERY)

cancel a job given its job_id

cancelJob = batchSQLClient.cancel(job_id) ```

COPY queries

COPY queries allow you to use the PostgreSQL COPY command for efficient streaming of data to and from CARTO.

Here is a basic example of its usage:

```python from carto.sql import SQLClient from carto.sql import CopySQLClient

sqlclient = SQLClient(authclient) copyclient = CopySQLClient(authclient)

Create a destination table for the copy with the right schema

sqlclient.send(""" CREATE TABLE IF NOT EXISTS copyexample ( thegeom geometry(Geometry,4326), name text, age integer ) """) sqlclient.send("SELECT CDBCartodbfyTable(currentschema, 'copy_example')")

COPY FROM a csv file in the filesytem

fromquery = 'COPY copyexample (thegeom, name, age) FROM stdin WITH (FORMAT csv, HEADER true)' result = copyclient.copyfromfilepath(fromquery, 'copyfrom.csv')

COPY TO a file in the filesystem

toquery = 'COPY copyexample TO stdout WITH (FORMAT csv, HEADER true)' copyclient.copytofilepath(toquery, 'export.csv') ```

Here's an equivalent, more pythonic example of the COPY FROM, using a file object:

python with open('copy_from.csv', 'rb') as f: copy_client.copyfrom_file_object(from_query, f)

And here is a demonstration of how to generate and stream data directly (no need for a file at all):

python def rows(): # note the \n to delimit rows yield bytearray(u'the_geom,name,age\n', 'utf-8') for i in range(1,80): row = u'SRID=4326;POINT({lon} {lat}),{name},{age}\n'.format( lon = i, lat = i, name = 'fulano', age = 100 - i ) yield bytearray(row, 'utf-8') copy_client.copyfrom(from_query, rows())

For more examples on how to use the SQL API, please refer to the examples folder or the API docs.

Import API

You can import local or remote datasets into CARTO like this:

```python from carto.datasets import DatasetManager

write here the path to a local file or remote URL

LOCALFILEOR_URL = ""

datasetmanager = DatasetManager(authclient) dataset = datasetmanager.create(LOCALFILEORURL) ```

The Import API is asynchronous, but the DatasetManager waits a maximum of 150 seconds for the dataset to be uploaded, so once it finishes the dataset has been created in CARTO.

Import a sync dataset

You can do it in the same way as a regular dataset, just include a sync_time parameter with a value >= 900 seconds

```python from carto.datasets import DatasetManager

how often to sync the dataset (in seconds)

SYNC_TIME = 900

write here the URL for the dataset to sync

URLTODATASET = ""

datasetmanager = DatasetManager(authclient) dataset = datasetmanager.create(URLTODATASET, SYNCTIME) ```

Alternatively, if you need to do further work with the sync dataset, you can use the SyncTableJobManager

```python from carto.sync_tables import SyncTableJobManager import time

how often to sync the dataset (in seconds)

SYNC_TIME = 900

write here the URL for the dataset to sync

URLTODATASET = ""

syncTableManager = SyncTableJobManager(authclient) syncTable = syncTableManager.create(URLTODATASET, SYNCTIME)

return the id of the sync

syncid = syncTable.getid()

while(syncTable.state != 'success'): time.sleep(5) syncTable.refresh() if (syncTable.state == 'failure'): print('The error code is: ' + str(syncTable.errorcode)) print('The error message is: ' + str(syncTable.errormessage)) break

force sync

syncTable.refresh() syncTable.force_sync() ```

Get a list of all the current import jobs

```python from carto.file_import import FileImportJobManager

fileimportmanager = FileImportJobManager(authclient) fileimports = fileimportmanager.all() ```

Get all the datasets

```python from carto.datasets import DatasetManager

datasetmanager = DatasetManager(authclient) datasets = dataset_manager.all() ```

Get a specific dataset

```python from carto.datasets import DatasetManager

write here the ID of the dataset to retrieve

DATASET_ID = ""

datasetmanager = DatasetManager(authclient) dataset = datasetmanager.get(DATASETID) ```

Update the properties of a dataset (non-public API) ```python from carto.datasets import DatasetManager from carto.permissions import PRIVATE, PUBLIC, LINK

write here the ID of the dataset to retrieve

DATASET_ID = ""

datasetmanager = DatasetManager(authclient) dataset = datasetmanager.get(DATASETID)

make the dataset PUBLIC

dataset.privacy = PUBLIC dataset.save() ```

Delete a dataset

```python from carto.datasets import DatasetManager

write here the ID of the dataset to retrieve

DATASET_ID = ""

datasetmanager = DatasetManager(authclient) dataset = datasetmanager.get(DATASETID) dataset.delete() ```

Export a CARTO visualization (non-public API)

```python from carto.visualizations import VisualizationManager

write here the name of the map to export

MAP_NAME = ""

visualizationmanager = VisualizationManager(authclient) visualization = visualizationmanager.get(MAPNAME)

url = visualization.export()

the URL points to a .carto file

print(url) ```

Please refer to the source code documentation and the examples folder to find out about the rest of the parameters accepted by constructors and methods.

Maps API

The Maps API allows to create and instantiate named and anonymous maps:

```python from carto.maps import NamedMapManager, NamedMap import json

write the path to a local file with a JSON named map template

JSON_TEMPLATE = ""

namedmapmanager = NamedMapManager(authclient) namedmap = NamedMap(namedmapmanager.client)

with open(JSONTEMPLATE) as namedmapjson: template = json.load(namedmap_json)

Create named map

named = namedmapmanager.create(template=template) ```

```python from carto.maps import AnonymousMap import json

write the path to a local file with a JSON named map template

JSON_TEMPLATE = ""

anonymous = AnonymousMap(authclient) with open(JSONTEMPLATE) as anonymousmapjson: template = json.load(anonymousmapjson)

Create anonymous map

anonymous.instantiate(template) ```

Instantiate a named map

```python from carto.maps import NamedMapManager, NamedMap import json

write the path to a local file with a JSON named map template

JSON_TEMPLATE = ""

write here the ID of the named map

NAMEDMAPID = ""

write here the token you set to the named map when created

NAMEDMAPTOKEN = ""

namedmapmanager = NamedMapManager(authclient) namedmap = namedmapmanager.get(NAMEDMAPID)

with open(JSONTEMPLATE) as templatejson: template = json.load(template_json)

namedmap.instantiate(template, NAMEDMAP_TOKEN) ```

Work with named maps

```python from carto.maps import NamedMapManager, NamedMap

write here the ID of the named map

NAMEDMAPID = ""

get the named map created

namedmap = namedmapmanager.get(NAMEDMAP_ID)

update named map

namedmap.view = None namedmap.save()

delete named map

named_map.delete()

list all named maps

namedmaps = namedmap_manager.all() ```

For more examples on how to use the Maps API, please refer to the examples folder or the API docs.

API Documentation

API documentation is written with Sphinx. To build the API docs:

pip install sphinx pip install sphinx_rtd_theme cd doc make html

Docs are generated inside the doc/build/hmtl folder. Please refer to them for a complete list of objects, functions and attributes of the carto-python API.

non-public APIs

Non-public APIs may change in the future and will thrown a warnings.warn message when used.

Please be aware if you plan to run them on a production environment.

Refer to the API docs for a list of non-public APIs

Examples

Inside the examples folder there are sample code snippets of the carto-python client.

To run examples, you should need to install additional dependencies:

pip install -r examples/requirements.txt

carto-python examples need to setup environment variables.

  • CARTO_ORG: The name of your organization
  • CARTOAPIURL: The base_url including your user and/or organization
  • CARTOAPIKEY: Your user API key

Please refer to the examples source code for additional info about parameters of each one

Owner

  • Name: CARTO
  • Login: CartoDB
  • Kind: organization
  • Email: support@cartodb.com
  • Location: Everywhere

The leading platform for Location Intelligence and Spatial Data Science

GitHub Events

Total
  • Fork event: 1
Last Year
  • Fork event: 1

Committers

Last synced: about 1 year ago

All Time
  • Total Commits: 600
  • Total Committers: 35
  • Avg Commits per committer: 17.143
  • Development Distribution Score (DDS): 0.752
Past Year
  • Commits: 0
  • Committers: 0
  • Avg Commits per committer: 0.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Alberto Romeu a****r@c****m 149
Rafa de la Torre r****e@c****m 99
Simon Martín o****d@g****m 95
Rohan Sharan s****n@b****u 38
Iñigo Medina i****a@c****m 33
javi q****c@g****m 28
Dani Carrion d****l@c****m 27
Jesús Arroyo Torrens j****o@c****m 22
Juan Ignacio Sánchez Lara j****l@g****m 14
Daniel García Aubert d****t@g****m 11
oriolbx o****x@g****m 10
Javier Goizueta j****a@g****m 9
Dani Carrión d****i@c****m 7
elenatorro e****o@g****m 6
Andy Eschbacher a****r@g****m 5
Javier G. Sogo j****o@g****m 5
Alberto Romeu a****r 5
jesusbotella j****a@g****m 5
javi j****i@a****s 4
Aaron Steele e****e@g****m 4
Mario de Frutos e****d@g****m 4
Jorge Sanz j****z@c****m 3
dsm5 d****6@g****m 3
Álex González a****o@g****m 2
moicalcob m****o@c****m 2
Jorge Sanz x****z@g****m 1
Juan Carlos Méndez j****z@g****m 1
Luis Bosque l****o@g****m 1
Mike Dillion m****n@g****m 1
simon hope s****e@g****u 1
and 5 more...
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 11 months ago

All Time
  • Total issues: 43
  • Total pull requests: 59
  • Average time to close issues: 3 months
  • Average time to close pull requests: 16 days
  • Total issue authors: 20
  • Total pull request authors: 17
  • Average comments per issue: 1.72
  • Average comments per pull request: 1.37
  • Merged pull requests: 54
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 1
  • Pull requests: 0
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 1
  • Pull request authors: 0
  • Average comments per issue: 1.0
  • Average comments per pull request: 0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • alrocar (10)
  • andy-esch (7)
  • oleurud (5)
  • kareemzok (2)
  • oriolbx (2)
  • juanignaciosl (2)
  • jgoizueta (2)
  • MichaelSpichiger (1)
  • ramiroaznar (1)
  • chrowe (1)
  • gmorain (1)
  • michellemho (1)
  • ztephm (1)
  • gelin (1)
  • tech-team-rural-mda (1)
Pull Request Authors
  • oleurud (15)
  • alrocar (12)
  • rafatower (6)
  • Jesus89 (5)
  • juanignaciosl (4)
  • dgaubert (2)
  • ethervoid (2)
  • oriolbx (2)
  • inigomedina (2)
  • jgoizueta (2)
  • jesusbotella (1)
  • danicarrion (1)
  • javitonino (1)
  • moicalcob (1)
  • andy-esch (1)
Top Labels
Issue Labels
enhancement (2) cf-1.0.0 (2) bug (1)
Pull Request Labels
enhancement (2) do not merge yet (1)

Packages

  • Total packages: 2
  • Total downloads:
    • pypi 11,074 last-month
  • Total dependent packages: 4
    (may contain duplicates)
  • Total dependent repositories: 28
    (may contain duplicates)
  • Total versions: 32
  • Total maintainers: 3
pypi.org: carto

SDK around CARTO's APIs

  • Versions: 30
  • Dependent Packages: 4
  • Dependent Repositories: 28
  • Downloads: 11,074 Last month
  • Docker Downloads: 0
Rankings
Downloads: 0.2%
Dependent packages count: 1.9%
Dependent repos count: 2.7%
Average: 3.3%
Docker downloads count: 4.1%
Forks count: 5.4%
Stargazers count: 5.7%
Maintainers (3)
Last synced: 11 months ago
conda-forge.org: carto
  • Versions: 2
  • Dependent Packages: 0
  • Dependent Repositories: 0
Rankings
Forks count: 20.7%
Stargazers count: 26.2%
Average: 33.0%
Dependent repos count: 34.0%
Dependent packages count: 51.2%
Last synced: 11 months ago

Dependencies

doc/requirements.txt pypi
  • pyrestcli >=0.6.3
  • requests >=2.7.0
  • sphinx_rtd_theme *
examples/nexrad/requirements.txt pypi
  • enum34 >=1.1.6
  • numpy >=1.15.1
  • siphon >=0.8.0
examples/requirements.txt pypi
  • configparser >=3.5.0
  • pandas >=0.24.2
  • prettytable *
  • pyrestcli >=0.6.4
  • requests >=2.7.0
requirements.txt pypi
  • pyrestcli ==0.6.11
  • requests >=2.7.0
test_requirements.txt pypi
  • pytest * test
  • pytest-mock * test
  • requests_mock >=1.3.0 test