如何在ThreadPool执行的函数中只发送一次电子邮件?

时间:2017-07-11 10:21:29

标签: python multithreading email threadpool threadpoolexecutor

这是我用来使API操作快10倍的函数:

def load_url(req, id, data, timeout):
    headers = {'Authorization': 'AT-API 111111222222333333344444445555555'}
    r = req.post("https://service.com/api/v1/compare", headers=headers, data=data, timeout=timeout)
    data = r.json()
    print id
    if data['error']:
        print data['error']
    else:
        c.execute("UPDATE offers SET valid = ? WHERE id = ?", ('valid' if data['data']['success'] else 'invalid', id))
        print data['data']['success']
        print data['data']['count']
    return r.json()


if __name__ == '__main__':
    ...
    with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
        future_to_url = {executor.submit(load_url, s, data['id'], data, 120): data for data in datas}
        for future in concurrent.futures.as_completed(future_to_url):
            url = future_to_url[future]
            try:
                data = future.result()

我们每4小时定期运行此脚本。在load_url中,我们打印并检查请求的状态,数据['数据'] ['计数'] - 是一个月保留的通话量。我想在达到5000次或更少的电话后发送电子邮件通知,但仅限一次。如何实现只发送一条消息,但不是5而不是50?我们正在使用Sqlite3来存储数据。

我们正在使用Mailgun发送电子邮件:

def send_simple_message(email_list):
    for email in email_list:
        response = requests.post(
            "https://api.mailgun.net/v3/newsletter.company.com",
            auth=("api", "key-1234567"),
            data={"from": "Mailgun Sandbox <postmaster@newsletter.mobupps.com>",
                "to": email,
                "subject": "Agent - we reached the limit by API",
                "html": "We reached the limit for agent" })

1 个答案:

答案 0 :(得分:1)

您可以使用锁定机制来阻止多个线程执行#left #coverage>div:nth-of-type(2)>div { color: red; }功能,并设置一个同步值来跟踪邮件是否已发送。

<div id="left">
  <div id="coverage">
    <h3>coverage</h3>
    <!-- first div -->
    <div>
      <div>
        <span>left->coverage->div 1->inner div 1->span text</span>
      </div>

      <div>
        <span>left->coverage->div 1->inner div 2->span text</span>
      </div>
    </div>

    <!-- second div -->
    <div>

      <!-- div to be accessed -->
      <div>
        <span>left->coverage->div 2->inner div 1->span text</span>
      </div>

    </div>
  </div>
</div>