Python 3 线程 post 请求传递 header 参数和数据
Python 3 threading post request passing header params and data
我正在努力使我的 post 请求更快,因为目前每个 post 需要 3 秒。因为我需要迭代它 n 次,所以可能需要几个小时。因此,我开始寻找线程、异步调用和许多其他方法,但 none 解决了我的问题。大多数问题是由于我无法指定 header 和我的 post 请求的参数。
我的Python版本是3.6.7
我的代码:
for i in range(0, 1000):
assetId = jsonAssets[i]['id']
uuidValue = uuid.uuid4()
headers = {'Content-Type': 'application/json',}
params = (('remember_token', '123456'),)
data = ('{{"asset":'
'{{"template":1,'
'"uuid":"{uuidValue}", '
'"assetid":{assetId}}}}}'
.format(uuidValue = uuidValue,
assetId = assetId))
response = requests.post('http://localhost:3000/api/v1/assets', headers=headers, params=params, data=data)
部分尝试使用:
pool.apply_async
或
ThreadResponse
但我无法像 request.post
中那样设置 headers 或参数
那么,如何使用这个 header、参数和数据更快地发出这个 post 请求?
提前致谢,抱歉给您带来任何麻烦,这是我的第一个 Whosebug post。
你应该使用像 aiohttp
这样的异步库
如果你可以正确地发出单个请求,最短的方法是使用ThreadPoolExecutor:
def single_request(i):
assetId = jsonAssets[i]['id']
uuidValue = uuid.uuid4()
# ... all other requests stuff here
return response
with ThreadPoolExecutor(max_workers=10) as executor:
futures = {
executor.submit(single_request, i): i
for i
in range(1000)
}
for future in as_completed(futures):
i = futures[future]
try:
res = future.result()
except Exception as exc:
print(f'excepiton in {i}: {exc}')
else:
print(res.text)
我正在努力使我的 post 请求更快,因为目前每个 post 需要 3 秒。因为我需要迭代它 n 次,所以可能需要几个小时。因此,我开始寻找线程、异步调用和许多其他方法,但 none 解决了我的问题。大多数问题是由于我无法指定 header 和我的 post 请求的参数。
我的Python版本是3.6.7
我的代码:
for i in range(0, 1000):
assetId = jsonAssets[i]['id']
uuidValue = uuid.uuid4()
headers = {'Content-Type': 'application/json',}
params = (('remember_token', '123456'),)
data = ('{{"asset":'
'{{"template":1,'
'"uuid":"{uuidValue}", '
'"assetid":{assetId}}}}}'
.format(uuidValue = uuidValue,
assetId = assetId))
response = requests.post('http://localhost:3000/api/v1/assets', headers=headers, params=params, data=data)
部分尝试使用:
pool.apply_async
或
ThreadResponse
但我无法像 request.post
中那样设置 headers 或参数那么,如何使用这个 header、参数和数据更快地发出这个 post 请求?
提前致谢,抱歉给您带来任何麻烦,这是我的第一个 Whosebug post。
你应该使用像 aiohttp
这样的异步库如果你可以正确地发出单个请求,最短的方法是使用ThreadPoolExecutor:
def single_request(i):
assetId = jsonAssets[i]['id']
uuidValue = uuid.uuid4()
# ... all other requests stuff here
return response
with ThreadPoolExecutor(max_workers=10) as executor:
futures = {
executor.submit(single_request, i): i
for i
in range(1000)
}
for future in as_completed(futures):
i = futures[future]
try:
res = future.result()
except Exception as exc:
print(f'excepiton in {i}: {exc}')
else:
print(res.text)