1010from canvasapi import Canvas
1111from canvasapi .course import Course
1212from drf_spectacular .utils import extend_schema
13+ from asgiref .sync import async_to_sync
1314
1415from .exceptions import CanvasErrorHandler , HTTPAPIError
1516
@@ -79,7 +80,7 @@ def post(self, request: Request, course_id: int) -> Response:
7980 course = Course (canvas_api ._Canvas__requester , {'id' : course_id })
8081
8182 start_time : float = time .perf_counter ()
82- results = asyncio . run ( self .create_sections (course , sections ) )
83+ results = self .create_sections (course , sections )
8384 end_time : float = time .perf_counter ()
8485 logger .info (f"Time taken to create { len (sections )} sections: { end_time - start_time :.2f} seconds" )
8586
@@ -96,10 +97,17 @@ def post(self, request: Request, course_id: int) -> Response:
9697 # Handle errors
9798 self .canvas_error .handle_canvas_api_exceptions (err_res )
9899 return Response (self .canvas_error .to_dict (), status = self .canvas_error .to_dict ().get ('statusCode' ))
99-
100+
101+ async def sem_task (self , semaphore , course , name ):
102+ async with semaphore :
103+ return await self .create_section (course , name )
104+
105+ @async_to_sync
100106 async def create_sections (self , course : Course , section_names : list ):
101- """Creates multiple sections concurrently."""
102- tasks = [self .create_section (course , name ) for name in section_names ]
107+ """Creates multiple sections concurrently, guarded by a semaphore."""
108+ max_concurrent = 10 # Set your desired concurrency limit here
109+ semaphore = asyncio .Semaphore (max_concurrent )
110+ tasks = [self .sem_task (semaphore , course , name ) for name in section_names ]
103111 return await asyncio .gather (* tasks , return_exceptions = True )
104112
105113 def create_section_sync (self , course : Course , section_name : str ):
0 commit comments