[英]how can i send payload with multiple requests in python using threadpoolexecutor and requests?
我已設法通過 ThreadPoolExecutor 同時向 web api 發送多個請求並獲得 json 響應(但我無法向我發送帶有有效負載的請求,但我無法向我發送帶有有效負載的請求,請參閱我的標題代碼並編輯您將發送足夠的有效負載的請求) 我只是不知道如何發送有效載荷。
from concurrent.futures import ThreadPoolExecutor
import requests
from timer import timer
URL = 'whatever.com'
payload = {'aaaaa': '0xxxxxxx'}
headers = {
'abc': 'xyz',
'Content-Type': 'application/json',
}
def fetch(session, url):
with session.post(url) as response:
print(response.json())
@timer(1, 1)
def main():
with ThreadPoolExecutor(max_workers=100) as executor:
with requests.session() as session:
executor.map(fetch, [session] * 100, [URL] * 100)
executor.shutdown(wait=True)
通常,您在調用post
方法時使用data關鍵字參數指定“有效負載”。 但是如果你想以 JSON 格式發送它,那么你應該使用json關鍵字參數:
session.post(url, json=payload, headers=headers)
(如果 header 指定'Content-Type': 'application/json'
,就像你的那樣,並且如果payload
已經是JSON
字符串,而你的不是,那么使用data關鍵字參數是正確的,那么你會not need any JSON conversion. But here you clearly need to first have requests
convert a Python dictionary to a JSON string for transmission and that is why the json argument is being used. You do not really need to explicitly specify a header argument since requests
will給你一個合適的。)
現在我知道這只是一個“虛擬”程序,它獲取相同的 URL 100 次。 在更現實的版本中,您將獲取 100 個不同的 URL,但您當然會在每次調用fetch
時使用相同的Session
實例。 因此,您可以通過以下方式簡化程序:
from functools import partial
...
def main():
with ThreadPoolExecutor(max_workers=100) as executor:
with requests.Session() as session:
worker = partial(fetch, session) # first argument will be session
executor.map(worker, [URL] * 100)
# remove following line
#executor.shutdown(wait=True)
請注意,我還注釋掉了您對方法shutdown
的顯式調用,因為在with... as executor:
塊終止后將自動調用shutdown
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.