python异步发布请求

标签 python python-requests python-asyncio aiohttp

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

关于python异步发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699817/

相关文章:

python - 元组解包顺序更改分配的值

python - 如何在 xonsh 提示符中有条件地使用 {env_name}

python - 使用 Python 请求访问经过身份验证的页面

python - 如何使用 asyncio 使 python 装饰器函数在 n 秒内重新安排函数?

Python - 将数组拆分为多个数组

python - 将单独的时间和日期列合并为 pandas 中的一列

python - 尝试从链接下载视频时出现 403 Forbidden - Python

Python从网页解析表格

python-3.x - 线程和异步: Task was destroyed but it is pending

python - 跨多进程共享基于异步等待协程的复杂对象