我能够读取 CSV,填充 JSON 对象,然后将“update.user”调用发布到端点,但我不知道如何批量执行相同操作(一次 50 条记录) .
这是它想要的 Json Body 的一个例子:
{
"users": [
{
"email": "string",
"dataFields": {},
"userId": "string",
"preferUserId": true,
"mergeNestedObjects": true
}
]
}
这是我按用户发布更新的代码。如何一次为 50 个用户批量执行此操作?
import requests
import json
import csv
import pdb
with open('john2.csv', 'r') as csv_file:
csv_file = csv.reader(csv_file)
next(csv_file)
for line in csv_file :
#print(line[2])
headers = {"Content-Type": "application/json",
"Accept": "application/json"
}
body = {"email": line[2],
"dataFields": {"firstName": line[0],
"lastName" : line[1],
"favoriteTomatoe" : line[3],
"totalTomatoOrders" : line[4],
"daysSinceLastOrder" : line[5],
"zip" : line[6],
"phoneNumber" : line[7],
"age" : line[8],
"streetAddress" : line[9],
"city" : line[10],
"state" : line[11],
"customMessageOne" : line[12],
"gender" : line[13]
}
}
body = json.dumps(body)
res = requests.request("POST",
"https://api.iterable.com/api/users/update?apiKey="key"",
headers=headers, data=body)
print(res.url + "\n" + str(res.status_code) + res.text)
感谢您的帮助!
请您参考如下方法:
看看这个片段:
user_list = get_users() # ['user_1', 'user_2', ... , 'user_n']
TOTAL_USERS = len(user_list)
session = requests.Session()
try:
# Add logic to read each user from user_list, then modify for loop below.
for user in user_list:
print("Testing user {}").format(user)
response = session.post(
URL,
data=predict_request)
response.raise_for_status()
total_time += response.elapsed.total_seconds()
print('Num requests: {} Avg latency: {} ms'.format(TOTAL_USERS, (
total_time * 1000) / TOTAL_USERS))
# You may do something here for each request
except requests.exceptions.HTTPError as err:
logging.exception(err)
if err.response.status_code == 400:
logging.exception('Server error %s', URL)
return
if err.response.status_code == 404:
logging.exception('Page not found %s', URL)
您只需要从用户列表中读取并用每个用户替换 for 循环。
