Python-Mailchimp批处理PUT请求

时间:2018-10-08 21:07:13

标签: python python-requests mailchimp

我正在尝试对Mailchimp API使用批处理功能。我当前的设置是这样的

operations = []
for idx, row in users_df.iterows():
    payload = {
        'email': row['email'],
        'last_updated': row['new_time'],
        'custom_value': row['new_value']
    }
    operation_item = {
        "method": "POST", # I changed this to PUT
        "path": '/lists/members/12345',
        "body": json.dumps(payload),
    }
    operations.append(operation_item)
client = mc.MailChimp(MAILCHIMP_TOKEN, MAILCHIMP_USER)
batch = client.batches.create(data={"operations": operations})

每当我使用POST方法时,都会出现此错误:old_user@gmail.com is already a list member. Use PUT to insert or update list members.

但是每当我将方法更改为PUT时,都会出现另一个错误:The requested method and resource are not compatible. See the Allow header for this resource's available methods.

有没有办法克服这个问题?我已经看过this,而this在Ruby中是一个类似的问题。

1 个答案:

答案 0 :(得分:0)

您无法对列表资源"/lists/members/12345"进行PUT操作,您需要将路径更改为"/lists/members/12345/{email}"

此代码对我们有用:

def add_users_to_mailchimp_list(list_id, users):
operations = []
client = get_mailchimp_client()

for user in users:
    member = {
        'email_address': user.email,
        'status_if_new': 'subscribed',
        'merge_fields': {
            'FNAME': user.first_name or '',
            'LNAME': user.last_name or '',
        },
    }
    operation_item = {
        "method": "PUT",
        "path": client.lists.members._build_path(list_id, 'members', user.email),
        "body": json.dumps(member),
    }
    operations.append(operation_item)
return client.batches.create(data={"operations": operations})

使用受保护的方法client.lists.members._build_path有点怪异,我想,如果您愿意手动构建网址,它将是f'lists/{list_id}/members/{user.email}'