python 异步 post 请求

python async post requests

我想知道是否有任何方法可以使此脚本更快 - 例如立即创建 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()

我觉得你发布的异步代码没问题。您可以通过将 asyncio 与 multithreading/multiprocess 结合使用来加快速度。

但是还有其他限制使您无法在一秒钟内创建 1000 个帐户。比如服务器端的网速、并发连接数、速率限制、数据库IOPS。

问题中的代码执行一系列的所有 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