Skip to content

Instantly share code, notes, and snippets.

@andrewxhill
Last active May 16, 2018 16:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewxhill/f9ca6e1de9138a2154c5abe3140315cd to your computer and use it in GitHub Desktop.
Save andrewxhill/f9ca6e1de9138a2154c5abe3140315cd to your computer and use it in GitHub Desktop.
quick example of using the batch api over python
import sys
import urllib
import urllib2
import json
import requests
# Start a new batch SQL task
def cartoBatchQuery(username, api_key, sql):
r = requests.post('http://%s.cartodb.com/api/v2/sql/job?api_key=%s' %(username,api_key),
headers={'content-type':'application/json'},
params={'query': urllib.quote_plus(sql)}
)
return r.json()
# Simply get the status of an ongoing job
def cartoBatchStatus(username, api_key, job_id):
r = requests.get('https://%s.cartodb.com/api/v2/sql/job/%s?api_key=%s' % (username,job_id,api_key))
return r.content #.json()
# If you "CREATE TABLE" in the batch API, you must "CartoDBify" it afterwards
def registerNewTable(username, api_key, table):
sql = "SELECT CDB_Cartodbfytable('%s')" % table
r = requests.post('http://%s.cartodb.com/api/v2/sql/job?api_key=%s' %(username,api_key),
headers={'content-type':'application/json'},
params={'query': urllib.quote_plus(sql)}
)
return r.json()
username = '{{username}}'
api_key = '{{api_key}}'
sql = "UPDATE australia_adm4 SET the_geom = ST_Centroid(the_geom)"
job = cartoBatchQuery(username,api_key,sql)
print job
status = cartoBatchStatus(username, api_key, job["job_id"])
print status
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment