Python - Mailchimp 批量 PUT 请求

Posted

技术标签:

【中文标题】Python - Mailchimp 批量 PUT 请求【英文标题】:Python - Mailchimp Batch PUT requests 【发布时间】:2019-03-13 14:07:15 【问题描述】:

我正在尝试使用 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】:

您不能对列表资源"/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 我想有点hacky,如果你喜欢你可以手动构建url,它将是f'lists/list_id/members/user.email'

【讨论】:

以上是关于Python - Mailchimp 批量 PUT 请求的主要内容,如果未能解决你的问题,请参考以下文章

php MailChimp列表订阅“put”请求

Mailchimp API Put 或 Patch 使用 Delphi REST

MailChimp API 3.0 批量/批量订阅

Mailchimp API 3.0 批量订阅 - Mailchimp3 PY

Mailchimp API 3.0 批量/批量取消标记

使用 Coldfusion/Railo 向 Mailchimp API v3.0 发送 PUT 请求时出现 401 未经授权的错误