Python - Mailchimp批量PUT请求

问题描述 投票:1回答:1

我正在尝试使用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方法时,我都会收到此错误:[email protected] 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.

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

python python-requests mailchimp
1个回答
0
投票

你不能做PUT到列表资源"/lists/members/12345",你需要改变路径为"/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有点hacky我想,如果你喜欢你可以手动建立网址,它将是f'lists/{list_id}/members/{user.email}'

© www.soinside.com 2019 - 2024. All rights reserved.