question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Await dont work in BackgroundTaks (Fastapi, Beanie, MongoDB)

See original GitHub issue

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • I commit to help with one of those options 👆

Example Code

from beanie import PydanticObjectId, Document
from fastapi import FastAPI, APIRouter, Request, BackgroundTasks
from time import time
from pydantic import BaseModel
from typing import Optional

app = FastAPI()
#router = APIRouter(prefix="/audit",tags=['Audit'])

class Audit(Document):
    account: Optional[str]
    company: Optional[str]
    user: Optional[str]
    module: str
    endpoint: str
    url_params: Optional[str]
    body_params: Optional[dict]
    reference_id: Optional[str]
    previous_state: Optional[bytes]
    posterior_state: Optional[bytes]
    date: int = time()

    class Settings:
        name = "audit"

async def review_audits() -> List[Audit]:
       audits = await Audit.find().limit(4).sort([("date", -1),]).to_list()
       print(audits)

@app.get("/query/", response_description="get audits to the database")
async def get_filter_audits(request: Request, background_tasks: BackgroundTasks) -> List[Audit]:
        desc = "We are working on it, you will be notified"
        reviews = {"hash":"12345678"}
        
        background_tasks.add_task(review_audits)
        
        return reviews

Description

when you call de endpoint return the result {“hash”:“12345678”} but the background task dont print the result founded on mongodb. I realized that the error occurs with version 0.85.0 but it works fine with version 0.78.0

Operating System

macOS

Operating System Details

No response

FastAPI Version

0.85.0

Python Version

3.10.9

Additional Context

No response

Issue Analytics

  • State:open
  • Created a year ago
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
vanishingESCkeycommented, Sep 23, 2022

@leaguidi if you use BaseHTTPMiddleware in your project then it may affect your BackgroundTasks, take a look at issues mentioned in https://github.com/encode/starlette/pull/1715#issue-1289392289

Read more comments on GitHub >

github_iconTop Results From Across the Web

FastAPI asynchronous background tasks blocks other requests?
Your task is defined as async , which means fastapi (or rather starlette) will run it in the asyncio event loop.
Read more >
Async Tests - FastAPI
As the testing function is now asynchronous, you can now also call (and await ) other async functions apart from sending requests to...
Read more >
Solve the drawbacks with FastAPI BackgroundTasks - Johachi
When using a background task, we do no longer need to wait for #1 , #2 , & #3 to complete before responding....
Read more >
TestDriven.io Authors
We are a team of software developers dedicated to teaching others how to build web applications with confidence.
Read more >
AsyncIOMotorClient – Connection to MongoDB — Motor 3.1.1 ...
This session is created uninitialized, use it in an await expression to initialize it, or an async with statement. async def coro(): collection...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found