Skip to main content
 首页 » 编程设计

python异步发布请求

2025年05月04日21Terrylee

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

请您参考如下方法:

问题中的代码执行一系列的所有 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 个同时连接。要增加或删除此限制,您必须在 session 中设置 custom connector。