【问题标题】:python async post requestspython异步发布请求
【发布时间】:2018-08-06 02:19:17
【问题描述】:

我想知道是否有任何方法可以让这个脚本变得更快 - 例如立即创建 1000 个帐户,或者至少在几秒钟内创建。 我自己尝试过做一些异步的东西,但这是我所能得到的,我只是异步编程的初学者,所以任何帮助都非常感谢。

import asyncio
import aiohttp


async def make_numbers(numbers, _numbers):
    for i in range(numbers, _numbers):
        yield i

async def make_account():
   url = "https://example.com/sign_up.php"
   async with aiohttp.ClientSession() as session:
          async for x in make_numbers(35691, 5000000):
              async with  session.post(url, data ={
                    "terms": 1,
                    "captcha": 1,
                    "email": "user%s@hotmail.com" % str(x),
                    "full_name": "user%s" % str(x),
                    "password": "123456",
                    "username": "auser%s" % str(x)
              }) as response:
                    data = await response.text()
                    print("-> Creating account number %d" % x)
                    print (data)

loop = asyncio.get_event_loop()
try:
    loop.run_until_complete(make_account())
finally:
    loop.close()

【问题讨论】:

    标签: python python-requests python-asyncio aiohttp


    【解决方案1】:

    问题中的代码以一系列方式执行所有 POST 请求,这使得代码不会比在单个线程中使用 requests 更快。但与requests 不同的是,asyncio 可以在同一个线程中并行化它们:

    async def make_account():
        url = "https://example.com/sign_up.php"
        async with aiohttp.ClientSession() as session:
            post_tasks = []
            # prepare the coroutines that post
            async for x in make_numbers(35691, 5000000):
                post_tasks.append(do_post(session, url, x))
            # now execute them all at once
            await asyncio.gather(*post_tasks)
    
    async def do_post(session, url, x):
        async with session.post(url, data ={
                    "terms": 1,
                    "captcha": 1,
                    "email": "user%s@hotmail.com" % str(x),
                    "full_name": "user%s" % str(x),
                    "password": "123456",
                    "username": "auser%s" % str(x)
              }) as response:
              data = await response.text()
              print("-> Created account number %d" % x)
              print (data)
    

    上面的代码将尝试一次发送所有的 POST 请求。尽管有此意图,但它会受到aiohttp.ClientSession 的 TCP 连接器的限制,默认情况下最多允许 100 个同时连接。要增加或消除此限制,您必须在会话上设置custom connector

    【讨论】:

      【解决方案2】:

      您发布的异步代码对我来说看起来不错。您可以通过将 asyncio 与多线程/多进程相结合来加快速度。

      但还有其他限制会阻止您在一秒钟内创建 1000 个帐户。例如,服务器端的网络速度、并发连接数、速率限制、数据库 IOPS。

      【讨论】:

        猜你喜欢
        • 2018-07-02
        • 1970-01-01
        • 2019-10-08
        • 1970-01-01
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-03
        相关资源
        最近更新 更多