'Post request with threading

Here is my snippet:

urls = ["http://goggle.com", "http://linux.com"]
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
data= {"k1": "v1"}
for url in urls:
    t = threading.Thread(target=requests.post, args=(url,), kwargs={'json': data, 'headers': headers})
    threads.append(t)
    t.start()

for thread in threads:
    thread.join()

But at the end I got this error TypeError: post() got multiple values for argument 'json'. So what is the appropriate way to call post request and to pass url, json and headers in threading lyb.



Solution 1:[1]

You have not set up your threading.Thread correctly. I advise wrapping up the target parameter in a function.

def post_requests(req):
    r=requests.post(req,json=data, headers=headers)
    print(r)
    return r

You don't need to include kwargs, then running your script with the following:

threads = []
for url in urls:
    t = threading.Thread(target=post_requests, args=(url,))
    
    threads.append(t)
    t.start()

for thread in threads:
    thread.join()

Your output:

<Response [405]>
<Response [200]>

You might want to check why "http://goggle.com" returns [405]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tesla john