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())
################################