Mailchimp 自动化 API returns 404 错误(找不到资源)

Mailchimp automation API returns 404 error (Resource not found)

我被分配了使用 MailChimp API 提取一些数据的任务。到目前为止,该脚本已经毫无问题地提取了报告、活动、列表和成员详细信息。但是,文档 here 中提到的工作流自动化 API 不起作用。事实上,该文档中给出的这个 CURL 示例给出了 404(未找到资源)错误:

curl --request GET \
--url 'https://usX.api.mailchimp.com/3.0/automations/b0a1c24f1a/emails' \
--user 'anystring:apikey' \
--include

我只用我自己的数据中心编号替换了 usX 并更新了我的 apiKey。无论如何,这是我的整个 automation.py python 脚本的自动化部分,我的用户抱怨:

#!/usr/bin/python
import urllib
import urllib2
import base64
import json
import csv
import sys
import os
import codecs
__version__ = "1.4"

##
# Configures the MailChimpExpress
reload(sys)
sys.setdefaultencoding('utf8')
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
workdir = "data/mailchimp/" 
workflow_id = "b0a1c24f1a"


##
# Writes a list to csv
#
# @param tname name of the csv file to output without extension
# @param tlist the python list to write
def write_to_csv(tname, tlist):
    myfile = open(workdir + tname + ".csv", 'wb')
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for li in tlist:
        wr.writerow(li)
    myfile.close()
    return tname + ".csv"

##
# Creates a file with specified name and text content.
#
# @param tname Name of the file with extension.
# @param ttext Content to write.
def createfile(tname, ttext):
    myfile = open(workdir + tname , 'w')
    myfile.write(ttext)
    myfile.close()

##
# Pulls data from Mailchimp automation API.
def run():
    key = sys.argv[1] # CAPTURE THE API KEY

    dc = key.split("-")[-1] #this is the data-center where your request goes
    username = "anystring" #could be literally anything as per mailchimp docs!
    output = "" #var to hold raw json
    data = "" #var to hold json dict
    cnt = 0 #counter to keep track of fetched objects

    ##
    # FETCH ALL REPORTS
    #
    campaigns = []
    baseurl = "https://" + dc + ".api.mailchimp.com/3.0/"
    psize, i = 1000, 0

    ##
    # Lets fetch the automation data
    #
    print "Now pulling automation data (UNSTABLE AND UNTESTED FEATURE)"
    autos = []
    data ={}
    #while(True): #No longer needed as there is no limit/offset here
    turl = baseurl + "automations/" +  workflow_id + "/emails" #lists/" + lid + "/members"
    print "turl is " + turl
    if False: #DEBUG:
        tfp = open('sample_workflow_response.json')
        output = tfp.read()
        tfp.close()
    else:
        request = urllib2.Request(turl)
        base64string = base64.encodestring('%s:%s' % (username, key)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)
        output = urllib2.urlopen(request).read()
    tdata = json.loads(output)
    tcnt = len(tdata['emails'])

    print tcnt, " emails pulled."
    print ""
    print 'ID', 'position', "create_time","start_time","archive_url"

    for email in tdata["emails"]:
        print email['id'], email['position'], email["create_time"], email["start_time"], email["archive_url"]

    MailChimpExpress.createfile("lastauto.json", output)

    ###
    print "All is well.."

if __name__ == "__main__":
    run()

当我运行上面的代码时,它给我以下输出:

Now pulling automation data (UNSTABLE AND UNTESTED FEATURE)
turl is https://us8.api.mailchimp.com/3.0/automations/b0a1c24f1a/emails
Traceback (most recent call last):
  File "./automation.py", line 97, in <module>
    run()
  File "./automation.py", line 80, in run
    output = urllib2.urlopen(request).read()
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 410, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 523, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 448, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 531, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 404: Not Found

我对 Mailchimp 会回答我关于 SO 的问题的期望这次没有实现!相反,我的客户不得不向 Mailchimp 寻求支持,他们是这样回答的:

  1. 首先,我们必须调用 /automations 端点来检索 "proper" workflow_id

  2. 然后,我们必须将上述结果用作 /automations/{workflow_id}/emails/ 端点的参数,并获取已发送的电子邮件和其他数据。

这个技巧奏效了,这里是修改后的部分代码供参考:

    ##
    # Lets fetch the automation data now
    #
    autos = []
    data ={}
    print "Now pulling automation data (UNSTABLE AND UNTESTED FEATURE)"
    turl = baseurl + "automations"  #lists/" + lid + "/members"
    print "turl is " + turl
    if DEBUG:
        tfp = open('sample_automation_response.json')
        output = tfp.read()
        tfp.close()
    else:
        request = urllib2.Request(turl)
        base64string = base64.encodestring('%s:%s' % (username, key)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)
        output = urllib2.urlopen(request).read()
    tdata = json.loads(output)
    tcnt = len(tdata['automations'])
    workflow_id = tdata['automations'][0]["id"]
    print tcnt, " automation settings pulled. The workflow_id is " + workflow_id

    print "Now pulling automation emails using workflow_id " + workflow_id + " (UNSTABLE AND UNTESTED FEATURE)"
    autos = []
    data ={}
    #while(True): #No longer needed as there is no limit/offset here
    turl = baseurl + "automations/" +  workflow_id + "/emails/" #lists/" + lid + "/members"
    print "turl is " + turl
    if DEBUG:
        tfp = open('sample_workflow_response.json')
        output = tfp.read()
        tfp.close()
    else:
        request = urllib2.Request(turl)
        base64string = base64.encodestring('%s:%s' % (username, key)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)
        output = urllib2.urlopen(request).read()
    tdata = json.loads(output)
    tcnt = len(tdata['emails'])

    print tcnt, " emails pulled."
    print ""
    print 'ID', 'position', "create_time","start_time","archive_url"

    for email in tdata["emails"]:
        print email['id'], email['position'], email["create_time"], email["start_time"], email["archive_url"]

    MailChimpExpress.createfile("lastauto.json", output)


    ###
    print "All is well.."