Skip to content

Instantly share code, notes, and snippets.

@lightstrike
Created September 10, 2016 01:04
Show Gist options
  • Save lightstrike/2ffb153c81c8d84e34c639e05430145b to your computer and use it in GitHub Desktop.
Save lightstrike/2ffb153c81c8d84e34c639e05430145b to your computer and use it in GitHub Desktop.
Setting User Attributes in Leanplum using Web API
import csv
from sys import argv
import requests
def transform_user_file(filename: str) -> []:
user_file = open(filename, 'r')
user_data = csv.reader(user_file)
# skip first row
next(user_data)
user_list = []
for user in user_data:
user_list.append({
'id': user[0].strip(),
'attributes': {
'firstName': user[1].strip(),
'lastName': user[2].strip(),
'phoneNumber': user[3].strip(),
'userType': user[4].strip(),
}
})
return user_list
def construct_base_leanplum_url(app_id: str, api_key: str) -> str:
BASE_LEANPLUM_API_URL = 'https://www.leanplum.com/api?appId={app_id}&clientKey={api_key}'
return BASE_LEANPLUM_API_URL.format(app_id=app_id, api_key=api_key)
def post_user_attributes_to_leanplum(base_leanplum_url: str,
user_id: str,
user_attributes: dict
) -> str:
LEANPLUM_USER_API_URL = '&userId={user_id}&apiVersion=1.0.6&action=setUserAttributes&userAttributes={user_attributes}'
user_leanplum_parameters = LEANPLUM_USER_API_URL.format(user_id=user_id, user_attributes=user_attributes)
set_user_attributes_url = ''.join([base_leanplum_url, user_leanplum_parameters])
response = requests.post(set_user_attributes_url)
return response.content.decode()
def set_leanplum_user_attributes(users_file: str, app_id: str, api_key: str) -> str:
user_list = transform_user_file(users_file)
base_leanplum_url = construct_base_leanplum_url(app_id, api_key)
for user in user_list:
api_response = post_user_attributes_to_leanplum(base_leanplum_url, user['id'], user['attributes'])
print(api_response)
if __name__ == '__main__':
try:
users_file = argv[1]
app_id = argv[2]
api_key = argv[3]
set_leanplum_user_attributes(users_file, app_id, api_key)
except IndexError:
raise Exception("Please specify a user file, app ID and API key.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment