使用Create Send与Python调用Campaign Monitor API获取订阅用户
我是Python及编程领域的新手,目前正在学习基础API课程,能够使用Postman与Flask进行基础API调用,但尚未接触过Createsend。我希望通过Campaign Monitor API获取所有订阅用户,反复查阅官方文档后得到了以下代码片段:
from __future__ import absolute_import import json from createsend.createsend import CreateSendBase, BadRequest from createsend.utils import json_to_py, validate_consent_to_track class Subscriber(CreateSendBase): """Represents a subscriber and associated functionality.""" def __init__(self, auth=None, list_id=None, email_address=None): self.list_id = list_id self.email_address = email_address super(Subscriber, self).__init__(auth) def get(self, list_id=None, email_address=None, include_tracking_preference=False): """Gets a subscriber by list ID and email address.""" params = { "email": email_address or self.email_address, "includetrackingpreference": include_tracking_preference, } response = self._get("/subscribers/%s.json" % (list_id or self.list_id), params=params) return json_to_py(response)
我对这段代码存在两点疑问:
- 是否需要在这段代码上方添加包含API密钥的Create Send类?
- 这段代码是否能返回完整的订阅用户JSON列表?
回答
嘿,我来帮你理清这两个问题:
1. 关于API密钥与认证的问题
是的,你必须配置认证信息才能让这段代码正常工作,但不需要自己手动写Create Send类。官方的createsend-python库已经帮我们封装好了认证相关的逻辑,你只需要在初始化Subscriber实例时传入包含API密钥的认证字典即可。
举个简单的示例:
# 导入官方库模块 from createsend import CreateSend # 配置你的API密钥 auth_config = {"api_key": "你的Campaign Monitor API密钥"} # 初始化Subscriber实例,传入认证信息和目标列表ID subscriber = Subscriber(auth=auth_config, list_id="目标订阅列表的ID")
这段代码里的Subscriber继承自CreateSendBase,而CreateSendBase需要认证凭据来完成API请求的签名,所以必须传入有效的认证信息(API密钥是新手最容易上手的方式)。
2. 关于获取完整订阅用户列表的问题
很遗憾,这段代码不能返回完整的订阅用户列表。它的get方法是用来根据指定邮箱地址查询单个订阅用户的详情的——你看方法参数里需要传入email_address,而且方法注释也明确写了"Gets a subscriber by list ID and email address"。
如果要获取某个列表下的所有订阅用户,你需要使用官方库中List类的subscribers方法,还要注意处理API的分页机制(因为Campaign Monitor API会分页返回大量数据)。这里给你一个完整的示例:
from createsend import List import json # 配置认证信息 auth_config = {"api_key": "你的API密钥"} target_list_id = "你的目标订阅列表ID" # 初始化List实例 list_client = List(auth=auth_config, list_id=target_list_id) all_subscribers = [] current_page = 1 # 循环获取所有分页的订阅用户 while True: # 获取当前页的订阅数据,page_size可设为最大允许的1000 page_data = list_client.subscribers(page=current_page, page_size=1000) all_subscribers.extend(page_data.Results) # 判断是否已到最后一页 if page_data.NumberOfPages <= current_page: break current_page += 1 # 现在all_subscribers里就是该列表下的所有订阅用户 print(json.dumps(all_subscribers, indent=2))
这样就能把所有订阅用户都收集到all_subscribers列表里,你可以根据需要处理这些数据。
内容的提问来源于stack exchange,提问作者Umar.H

