88 views
Как вызвать фактически синхронную и блокирующую функцию `process_chunk` из асинхронного кода так, чтобы не блокировать event loop?
Asked at
AI answer
Move the blocking call to a separate thread, for example by using asyncio.to_thread:
result = await asyncio.to_thread(process_chunk, chunk)
This allows the event loop to continue running other tasks while the function is working. For older Python versions, you can use loop.run_in_executor(...).
Also asked at GigaChat / Сбер
- app = FastAPI() def get_db(): db = SessionLocal() try: yield db finally: db.close() def heavy_text_parser(file_id: int, db: Session): # Parsing a file that takes 5 minutes parse_and_save(file_id, db) @app.post("/upload") async def upload_file( background_tasks: BackgroundTasks, db: Session = Depends(get_db) ): file_id = save_file_to_db(db) db.commit() background_tasks.add_task(heavy_text_parser, file_id, db) return {"status": "parsing started"}
- def extract_emails_from_huge_file(file_path: str) -> list[str]: with open(file_path, 'r', encoding='utf-8') as f: content = f.read() # Заменяем переносы строк, чтобы текст был "сплошным" content = content.replace('\r\n', ' ').replace('\n', ' ') lines = content.split(' ') emails = [word for word in lines if '@' in word] return emails
Similar questions
- How can you efficiently make a synchronous request with requests in an asynchronous application?
- Conceptually, how is the Event Loop in asyncio structured?
- What happens if you call time.sleep inside a coroutine?
- What is asyncio? When is it better to use asyncio, and when should you use threads (threading)? How can you speed up heavy mathematical computations (CPU-bound) in Python?
- Приходилось ли писать многопоточный код на Python без asyncio (threading, multiprocessing)?