gpt4 book ai didi

python - 如何将关键字参数添加到通过 ThreadPoolExecuter 和 run_in_executor 调用的方法?

转载 作者:行者123 更新时间:2023-12-01 07:22:21 47 4
gpt4 key购买 nike

我正在尝试在 concurrent.futures 的帮助下同时发送 POST 请求。由于某种原因,我无法设置自定义 header 。我要设置

  1. 授权
  2. 内容类型

这是我到目前为止所取得的进展。

import asyncio
import concurrent.futures
import requests
from urllib.parse import urlencode, quote_plus


params = urlencode({'a': 'b', 'c': 'd', 'e': 'f'})
headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "*/*","Authorization": "Bearer kdjalskdjalskd"}

async def main():

with concurrent.futures.ThreadPoolExecutor(max_workers=20) as executor:

loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
requests.post,
'https://fac03c95.ngrok.io',params, headers)
for i in range(20)
]
for response in await asyncio.gather(*futures):
print(response.text)
pass

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

但由于某种原因, header 似乎没有显示在请求中。有人可以帮我吗?

提前致谢:)

最佳答案

免责声明:它是问题中描述的特定问题的解决方案。提高所提供代码的质量不是此答案的目的。

让我们查看 loop.run_in_executor() 的文档和 requests.post() .

run_in_executor() 将提供的参数传递给函数。现在让我们看一下您的代码:

loop.run_in_executor(executor, requests.post, 'https://fac03c95.ngrok.io', params, headers)

因此,结果函数将像这样被调用:

requests.post('https://fac03c95.ngrok.io', params, headers)

让我们将提供的参数值与其关键字合并:

  • 网址 - https://fac03c95.ngrok.io;
  • 数据 - {'a': 'b', 'c': 'd', 'e': 'f'}
  • json - {"Content-type": "application/x-www-form-urlencoded", ...}

要添加自定义 header ,您应该传递关键字参数 headers=。不幸的是,run_in_executor() 不转发关键字参数,因此您必须使用某种代理函数。以下是一些变体:

  1. 函数

    def proxy_post(url, data, headers):
    return requests.post(url, data=data, headers=headers)

    ...

    loop.run_in_executor(executor, proxy_post, 'https://fac03c95.ngrok.io', params, headers)
  2. lambda

    loop.run_in_executor(executor, lambda: requests.post('https://fac03c95.ngrok.io', data=params, headers=headers))
  3. functools.partial() .

    import functools

    ...

    loop.run_in_executor(executor, functools.partial(requests.post, 'https://fac03c95.ngrok.io', data=params, headers=headers))

关于python - 如何将关键字参数添加到通过 ThreadPoolExecuter 和 run_in_executor 调用的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57638380/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com