This is an example of how a program can use the Enterprise Users Management API to create, update or delete users from a CSV or a JSON file.
We use two python files: secrets.py
containing the owners credentials (name, API key and org name) and manage_users.py
with the code to be run.
# manage_users.py
# encoding: utf-8
# Usage:
# create_users.py <action> <filename>
#
# Supported actions:
# create
# update
# delete
#
# Supported file extensions
# .csv
# .json
import csv, json, sys
from httplib2 import Http
from urllib import urlencode
try:
from secrets import *
except Exception, e:
print('You need a secrets.py file')
supported_actions = {
'update': 'PUT',
'create': 'POST',
'delete': 'DELETE'
}
supported_extensions = ['.csv', '.json']
def main():
parse_arguments()
users = load_users_from_file(filename)
base_url = 'http://' + org_name + '.cartodb.com/u/' + owner_username + '/api/v1/organization/' + org_name + '/users/'
for user in users:
params = user.copy() # copy user attributes into params
params['api_key'] = api_key # add api key to params
url = base_url if action == 'create' else base_url + params['username']
response, content = Http().request(url, method, urlencode(params))
handle_response(response, content, user)
def load_users_from_file(filename):
if filename.endswith('.json'):
with open(filename) as users_file:
return json.load(users_file)['users']
elif filename.endswith('.csv'):
with open(filename) as users_file:
return list(csv.DictReader(users_file))
else:
print('File format not supported')
print_usage()
def handle_response(response, content, user):
code = response['status']
if code == '200':
print('%s user %s successful' % (action, user['username']))
elif code == '410':
print('Some params were wrong for %s:' % user['username'])
elif code == '401':
print('Auhtentication error.')
else:
print('Unknown error.')
print(content)
def parse_arguments():
global program_name, action, filename, method
try:
program_name = sys.argv[0]
action = sys.argv[1]
filename = sys.argv[2]
method = supported_actions[action]
except Exception, e:
print_usage()
sys.exit(-1)
def print_usage():
print("Usage:")
print("\t%s <action> <filename>" % program_name)
print
print("Supported actions:")
for action in supported_actions.keys():
print("\t%s" % action)
print
print("Supported file extensions")
for action in supported_extensions:
print("\t%s" % action)
print
if __name__ == '__main__':
main()
# secrets.py
API_KEY = '875e43adaa8fdd7ffec88aa5d38cf230403f656f'
ORG_NAME = 'niceorg'
OWNER_USERNAME = 'owner'
We also need a CSV file with the users' info:
# users.csv
username,email,password,quota_in_bytes,soft_geocoding_limit
bob,bob@niceorg.com,bobsecret!,,
alice,alice@niceorg.com,alicesecret!,,true
alex,alex@niceorg.com,alexsecret!,300000000,true
sandy,sandy@niceorg.com,sandysecret!,100000000,
or, alternatively, a JSON file:
# users.json
{
"users" : [
{
"username": "bob",
"email": "bob@niceorg.org",
"password": "bobsecret!"
},
{
"username": "alice",
"email": "alice@niceorg.org",
"password": "alicesecret!",
"soft_geocoding_limit": true
},
{
"username": "alex",
"email": "alex@niceorg.org",
"password": "alexsecret!",
"quota_in_bytes": 300000000,
"soft_geocoding_limit": true
},
{
"username": "sandy",
"email": "sandy@niceorg.org",
"password": "sandysecret!",
"quota_in_bytes": 100000000
}
]
}
Here are some examples of usage:
$ python manage_users.py create users.csv # creates users from users.csv
$ python manage_users.py delete users.json # deletes users in users.json
$ python manage_users.py update users.csv # updates users info for users.csv