如何使用 Python 查询所有 Mailchimp 活动的列表?

Posted

技术标签:

【中文标题】如何使用 Python 查询所有 Mailchimp 活动的列表?【英文标题】:How to query for a list of all Mailchimp campaigns using Python? 【发布时间】:2021-03-17 23:16:28 【问题描述】:

有活动;但是,没有一个是从这个sample 脚本返回的:

nicholas@mordor:~/python$ 
nicholas@mordor:~/python$ python3 chimp.py 
key          jfkdljfkl_key
user         fdjkslafjs_user
password     dkljfdkl_pword
server       fjkdls_server
nicholas@mordor:~/python$ 
nicholas@mordor:~/python$ cat chimp.py 
import os
from mailchimp3 import MailChimp

key=(os.environ['chimp_key'])
user=(os.environ['chimp_user'])
password=(os.environ['chimp_password'])
server=(os.environ['chimp_server'])

print ("key\t\t", key)
print ("user\t\t", user)
print ("password\t", password)
print ("server\t\t", server)


client = MailChimp(mc_api=key, mc_user=user)
client.lists.all(get_all=True, fields="lists.name,lists.id")
client.campaigns.all(get_all=True)


nicholas@mordor:~/python$ 

我是否需要发送其他信息才能取回广告系列列表?只是想记录一些来自 Mailchimp 的基本回复。

(显然,我没有发布我的API 密钥,也没有发布其他敏感信息。)

【问题讨论】:

【参考方案1】:

这是我使用并为我工作的东西。只需使用 MailChimp 客户端调用 get_all_campaigns 函数。我为我的特定需求添加了n_days,但如果您不需要它,您可以选择删除这部分代码。您还可以根据需要自定义重命名和删除列。

from typing import Optional, Union, List, Tuple
from datetime import timedelta, date
import pandas as pd  # type: ignore
from mailchimp3 import MailChimp # type: ignore


default_campaign_fields = [
    'id',
    'send_time',
    'emails_sent',
    'recipients.recipient_count',
    'settings.title',
    'settings.from_name',
    'settings.reply_to',
    'report_summary'
]

def get_campaigns(client: MailChimp, n_days: int = 7, fields: Optional[Union[str, List[str]]] = None) -> pd.DataFrame:
    """
    Gets the statistics for all sent campaigns in the last 'n_days' 
    
    client: (Required) MailChimp client object

    n_days: (int) Get campaigns for the last n_days

    fields: Specific fields to return. Default is None which gets some predefined columns.
    """
    keyword = 'campaigns'

    if fields is None:
        fields = default_campaign_fields  
    
    # If it is a string (single field), convert to List so that join operation works properly
    if isinstance(fields, str):
        fields = [fields]

    fields = [keyword + '.' + field for field in fields]
    fields = ",".join(fields)

    now = date.today()
    last_ndays = now - timedelta(days=n_days)
    
    rvDataFrame = pd.json_normalize(
        client.campaigns.all(
            get_all=True,
            since_send_time=last_ndays,
            fields=fields).get(keyword))
    if 'send_time' in rvDataFrame.columns:
        rvDataFrame.sort_values('send_time', ascending=False, inplace=True)
    
    mapper = 
        "id": "ID",
        "emails_sent": "Emails Sent",
        "settings.title": "Campaign Name",
        "settings.from_name": "From",
        "settings.reply_to": "Email",
        "report_summary.unique_opens": "Opens",
        "report_summary.open_rate": "Open Rate (%)",
        "report_summary.subscriber_clicks": "Unique Clicks",
        "report_summary.click_rate": "Click Rate (%)"
    
    
    drops = [
        "recipients.recipient_count",
        "report_summary.opens", 
        "report_summary.clicks",
        "report_summary.ecommerce.total_orders",
        "report_summary.ecommerce.total_spent",
        "report_summary.ecommerce.total_revenue"]

    rvDataFrame.drop(columns=drops, inplace=True)
    rvDataFrame.rename(columns=mapper, inplace=True)

    rvDataFrame.loc[:,"Open Rate (%)"] = round(rvDataFrame.loc[:,"Open Rate (%)"]*100,2)
    rvDataFrame.loc[:,"Click Rate (%)"] = round(rvDataFrame.loc[:,"Click Rate (%)"]*100,2)

    return rvDataFrame

【讨论】:

以上是关于如何使用 Python 查询所有 Mailchimp 活动的列表?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 Python 对大 XML 文件执行查询?

如何使用 Facebook 营销 api 在单个查询中获取所有广告的见解

如何在 dns-python 中进行 dns 查询作为 dig(带有附加记录部分)?

如何在 GQL 中查询过去 6 小时(日期时间)的所有条目?

使用 cassandra-python-driver 记录所有查询

如何使用 Python 单击 MS Access 上的按钮