簡體   English   中英

非常慢 http 在 python 中發布請求

[英]Very slow http post requests in python

我創建了一個 python 腳本,它從 facebook 圖形 Z8A5DA52ED126447D359E70C057 收集 json 數據並檢查用戶職位信息。

通過使用這個腳本,我通知用戶通過聊天機器人更新他們的 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)

請幫幫我....我該怎么辦?

此處調整示例...

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))

用您的square列表替換values ,用您的reply function 替換值,並將max_workers設置為您喜歡的數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM