82 views
async def get_user(user_id: int, db: AsyncSession): try: user = await db.get(User, user_id) return user finally: await db.close() return None q = get_user(76576, )
Asked at
AI answer
There are several problems in the example:
- The call
get_user(76576, )does not pass the requireddbargument, so it will immediately raise aTypeError. Also, the result ofasync defmust be obtained usingawait. return Noneinsidefinallywill always replace the result fromtryand suppress any exception that may have occurred.- If the session was passed in by the calling code, you generally should not close it inside the function: the session's lifecycle should be managed by its owner.
For example:
async def get_user(user_id: int, db: AsyncSession) -> User | None:
return await db.get(User, user_id)
async with async_session() as db:
user = await get_user(76576, db)
If the function creates the session itself, use its asynchronous context manager (async with) and do not add a return in `finally.
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
- async def get_user(user_id: int, db: AsyncSession): try: user = await db.get(User, user_id) return user finally: await db.close() return None a = await get_user(15, db) # a?
- How does the asynchronous context manager (`async with`) work?
- What is the downside of declaring a FastAPI endpoint as a regular synchronous function (`def`) if it waits for a response from a database or LLM model, compared with using `async def`?
- What is `Depends` in FastAPI, and when should you use it?
- Tell me about asyncio: what is it and how does it work?