【问题标题】:Python 3 threading post request passing header params and dataPython 3 线程发布请求传递标头参数和数据
【发布时间】:2019-01-04 21:59:57
【问题描述】:

我正在努力加快我的发帖请求,因为目前每个发帖需要 3 秒。因为我需要迭代它 n 次,所以可能需要几个小时。所以,我开始寻找线程、异步调用和许多其他方法,但没有一个能解决我的问题。大多数问题是由于我无法指定发布请求的标头和参数。

我的 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 中那样设置标题或参数

那么,如何使用此标头、参数和数据更快地发出此帖子请求?

提前致谢,如有任何麻烦,我们深表歉意,这是我的第一篇 stackoverflow 帖子。

【问题讨论】:

    标签: python-3.x python-requests python-asyncio python-multithreading


    【解决方案1】:

    如果你可以正确地发出单个请求,最简单的方法是使用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)
    

    【讨论】:

    • 您好 Mikhail,我尝试了您的解决方案,在使用范围 100 运行它后,执行此任务所花费的总时间比我之前的代码减少了 11 秒,从 121 秒减少到 110 秒。跨度>
    • @RafaelLobo 好吧,如果您请求 localhost,您不会看到任何重大变化。当您开始请求一些真实的域时,您应该会看到真实的结果。 Here's detailed explanation why。但是,如果您没有看到实际域的增加,我需要可重现的代码来提供帮助。
    • 谢谢米哈伊尔,我认为该链接解释了问题。我将在另一台服务器上尝试我的请求。
    • Mikhail,我刚刚在一台可以同时处理多个请求的服务器上对其进行了测试,它比我的本地主机服务器(一次只能处理一个请求)快 70%。感谢您的帮助!
    【解决方案2】:

    你应该使用像aiohttp这样的异步库

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多