簡體   English   中英

發送同時請求python(一次性全部)

[英]Send Simultaneous Requests python (all at once)

我正在嘗試創建一個腳本,同時向一個頁面發送超過1000個請求。 但是請求具有線程(1000)線程的庫。 似乎是在1秒內完成前50個左右的請求,而其他9950需要相當長的時間。 我是這樣測量的。

def print_to_cmd(strinng):
    queueLock.acquire()
    print strinng
    queueLock.release()

    start = time.time()
    resp = requests.get('http://test.net/', headers=header)
    end = time.time()

    print_to_cmd(str(end-start))

我認為請求庫限制了它們被發送的速度。

Doe的任何人都知道在python中同時發送請求的方式嗎? 我有一個200MB上傳的VPS,所以這不是與python或請求庫限制它的問題。 他們都需要在1秒內互相訪問網站。

感謝閱讀,我希望有人可以提供幫助。

我一般發現最好的解決方案是使用像龍卷風這樣的異步庫。 然而,我發現最簡單的解決方案是使用ThreadPoolExecutor。


import requests
from concurrent.futures import ThreadPoolExecutor

def get_url(url):
    return requests.get(url)
with ThreadPoolExecutor(max_workers=50) as pool:
    print(list(pool.map(get_url,list_of_urls)))

假設您知道自己在做什么,我首先建議您實施一個帶有抖動的退避策略,以防止“可預測的雷鳴般的囤積”到您的服務器。 也就是說,你應該考慮做一些threading

import threading
class FuncThread(threading.Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        threading.Thread.__init__(self)

    def run(self):
        self._target(*self._args)

所以你會做類似的事情

t = FuncThread(doApiCall, url)
t.start()

你的方法doApiCall定義如下

def doApiCall(self, url):

我知道這是一個老問題,但你現在可以使用asyncioaiohttp來做到這aiohttp

import asyncio
import aiohttp
from aiohttp import ClientSession

async def fetch_html(url: str, session: ClientSession, **kwargs) -> str:
    resp = await session.request(method="GET", url=url, **kwargs)
    resp.raise_for_status()
    return await resp.text()

async def make_requests(url: str, **kwargs) -> None:
    async with ClientSession() as session:
        tasks = []
        for i in range(1,1000):
            tasks.append(
                fetch_html(url=url, session=session, **kwargs)
            )
        results = await asyncio.gather(*tasks)
        # do something with results

if __name__ == "__main__":
    asyncio.run(make_requests(url='http://test.net/'))

您可以閱讀更多相關信息,並在此處查看示例。

暫無
暫無

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

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