0

I found some older posts related here but they were too old to rely on. like https://stackoverflow.com/questions/46727787/runtimeerror-there-is-no-current-event-loop-in-thread-in-async-apscheduler and https://stackoverflow.com/questions/48725890/runtimeerror-there-is-no-current-event-loop-in-thread-thread-1-multithreadi

I am pretty new to async functions.I had to fetch a pretty big data which was taking lot of time to load so had to switch over to async functions.My views.py looks somethings like this

import asyncio
from aiohttp import ClientSession

async def fetch(url, session):
    async with session.get(url) as response:
       return await response


async def bound_fetch(sem, url, session):
# Getter function with semaphore.
   async with sem:
      await fetch(url, session)


async def run(r):
  url = "http://myurl/{}"
  tasks = []
# create instance of Semaphore
  sem = asyncio.Semaphore(1000)

# Create client session that will ensure we dont open new connection
# per each request.
   async with ClientSession() as session:
      for i in range(0,r,10):
        # pass Semaphore and session to every GET request
         task = asyncio.ensure_future(bound_fetch(sem, url.format(i), session))
         tasks.append(task)

      responses = asyncio.gather(*tasks)
      await responses

number = 10000
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(number))
loop.run_until_complete(future)
Vivek Anand
  • 381
  • 1
  • 10

0 Answers0