【问题标题】:Very slow http post requests in pythonpython中非常慢的http post请求
【发布时间】:2020-12-29 14:47:23
【问题描述】:

我创建了一个 python 脚本,它从 facebook graph api 收集 json 数据并检查用户 job_title 信息。

通过使用这个脚本,我通知用户通过聊天机器人更新他们的 job_title,但是这个过程需要太多时间来向所有用户发送请求。

import json
import requests

users_url = Facebook API to fetch user details
MESSAGE_TO_SEND = '....PLEASE UPDATE JOB TITLE....'

ACCESS_TOKEN = Page_Access_token

def reply(user_id, msg,ACCESS_TOKEN):
    data = {
        "recipient": { "id": user_id },
        "message": { "text": msg }
    }

    resp = requests.post("https://graph.facebook.com/v9.0/me/messages?access_token="+ ACCESS_TOKEN, json=data)
    print('Message Sent to : ',user_id)
    # print(resp.content, resp, 'response from facebook')

def header(ACCESS_TOKEN):
    return {'Authorization': 'Bearer ' + ACCESS_TOKEN}

def user_data(ACCESS_TOKEN):
    
    headers = header(ACCESS_TOKEN)
    data = requests.get(users_url,headers=headers)
    result_json = json.loads(data.text)
    resources = result_json['Resources']
    
    for titles in range(0,len(resources)):
            if 'title' not in resources[titles]:
                user_id = str(resources[titles]['id'])
                reply(user_id, MESSAGE_TO_SEND,ACCESS_TOKEN)


user_data(ACCESS_TOKEN)

请帮帮我....我该怎么办?

【问题讨论】:

  • 欢迎来到 SO!您可以尝试生成多个线程。 resources 多久了? requests.post 是一个阻塞调用,但大部分是线程什么都不做,等待请求通过网络发出并返回响应。该进程可能正在处理其他请求,而不是坐在它的手上。
  • @ggorlen 大约 10000-20000
  • 谢谢。您预计 10k+ 请求大约需要多长时间?目前在您的机器上需要多长时间?
  • @ggorlen 发送 1 条通知大约需要 1 秒
  • 这能回答你的问题吗? Multiple async requests simultaneously

标签: python python-3.x python-2.7 python-requests facebook-chatbot


【解决方案1】:

改编示例here...

from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import as_completed
import time

def square(n):
    time.sleep(3.0)
    print( n * n )

def main():
    values = range(10)
    with ThreadPoolExecutor(max_workers = 5) as executor:
        results = executor.map(square, values)
    # for result in results:
        # print(result)

if __name__ == '__main__':
    st = time.time()
    main()
    et = time.time()
    print('{:.3f} seconds'.format(et-st))

values 替换为您的用户ID 列表,将square 替换为您的reply 函数,并将max_workers 设置为您喜欢的数字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 2011-10-29
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2017-02-14
    • 1970-01-01
    相关资源
    最近更新 更多