Below is a minimal reproducible example.
import asyncio
import aiohttp
from database_utils import connect_to_database
from pytdx.hq import TdxHq_API
api = TdxHq_API()
api.connect('119.147.212.81', 7709)
async def execute_main(conn, c):
try:
c.execute("SELECT stockCode, shsz FROM stocks")
rows = c.fetchall()
column_names = [description[0] for description in c.description]
results = [dict(zip(column_names, row)) for row in rows]
async with aiohttp.ClientSession() as session:
tasks = []
for result in results:
stock_code = result['stockCode'].strip()
market = result['shsz']
tasks.append(fetch_quote(session, api, market, stock_code, conn, c))
await asyncio.gather(*tasks)
except Exception as e:
print(f"An error occurred: {e}")
api.disconnect()
print("Execution completed.")
# Establish a connection to the database
conn, c = connect_to_database()
# Run the main function
loop = asyncio.get_event_loop()
loop.run_until_complete(execute_main(conn, c))
597 def _check_running(self):
598 if self.is_running():
--> 599 raise RuntimeError('This event loop is already running')
600 if events._get_running_loop() is not None:
601 raise RuntimeError(
602 'Cannot run the event loop while another loop is running')
When I use
asyncio.run(execute_main(conn, c))
I get:
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
File c:\Users\Steven\my-app\management\real.time.price2.py:52
49 conn, c = connect_to_database()
51 # Run the main function
---> 52 asyncio.run(execute_main(conn, c))
File c:\Python312\Lib\asyncio\runners.py:190, in run(main, debug, loop_factory)
161 """Execute the coroutine and return the result.
162
163 This function runs the passed coroutine, taking care of
(...)
186 asyncio.run(main())
187 """
188 if events._get_running_loop() is not None:
189 # fail fast with short traceback
--> 190 raise RuntimeError(
191 "asyncio.run() cannot be called from a running event loop")
193 with Runner(debug=debug, loop_factory=loop_factory) as runner:
194 return runner.run(main)
RuntimeError: asyncio.run() cannot be called from a running event loop
The current running event loop is: <_WindowsSelectorEventLoop running=True closed=False debug=False>