Twi*_*ler 1 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()
Run Code Online (Sandbox Code Playgroud)
问题中的代码将执行一系列的所有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 poat
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)
Run Code Online (Sandbox Code Playgroud)
上面的代码将尝试一次发送所有POST请求。尽管有此意图,但它aiohttp.ClientSession的TCP连接器会限制它的运行,默认情况下该连接器最多允许100个同时连接。要增加或消除此限制,必须在会话上设置自定义连接器。
| 归档时间: |
|
| 查看次数: |
4182 次 |
| 最近记录: |