aiohttp测试

 

 

 

import aiohttp
import asyncio

async def fetch(session, url, data):
    async with session.post(url, json=data) as response:
        return await response.text()

async def main():
    url = 'https://example.com/api/endpoint'
    data = {'key': 'value'}
    
    async with aiohttp.ClientSession() as session:
        try:
            # 设置超时时间为5秒
            html = await asyncio.wait_for(fetch(session, url, data), timeout=5)
            print(html)
        except asyncio.TimeoutError as e:
            # 处理超时异常
            print(f"请求超时: {e}")

# 运行主协程
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

 

 

 

 

################################

posted @ 2024-06-08 10:24  西北逍遥  阅读(5)  评论(0编辑  收藏  举报