Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
9 tasks done
leaguidi opened this issue Sep 16, 2022 · 10 comments
Closed
9 tasks done

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

leaguidi opened this issue Sep 16, 2022 · 10 comments

Comments

@leaguidi
Copy link

leaguidi commented Sep 16, 2022

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

@leaguidi leaguidi added the question Question or problem label Sep 16, 2022
@iudeen
Copy link
Contributor

iudeen commented Sep 16, 2022

You are not calling any function inside background Task.


@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}

@JarroVGIT
Copy link
Contributor

background_tasks.add_task() doesn’t add any task.

@leaguidi
Copy link
Author

leaguidi commented Sep 16, 2022 via email

@leaguidi
Copy link
Author

the code is correct now, sorry for my English.

@leaguidi leaguidi reopened this Sep 17, 2022
@JarroVGIT
Copy link
Contributor

JarroVGIT commented Sep 17, 2022

I cannot reproduce this using the following example:

import asyncio
from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


async def get_items_from_db():
    print("Get some items from DB..")
    await asyncio.sleep(1)
    return [1, 2, 3, 4]


async def background_task_function():
    print("Background task is executing..")
    result = await get_items_from_db()
    print(f"Items collected: {result}")


@app.get("/")
async def root(bt: BackgroundTasks):
    print("Endpoint is called, now adding BG task..")
    bt.add_task(background_task_function)
    print("BG task added, returning response..")
    return {"hello": "world"}


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8000)

The above example will print correctly when calling localhost:8000:

INFO:     Started server process [14322]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Endpoint is called, now adding BG task..
BG task added, returning response..
INFO:     127.0.0.1:55946 - "GET / HTTP/1.1" 200 OK
Background task is executing..
Get some items from DB..
Items collected: [1, 2, 3, 4]

The issue might be the actual call to Audit. Try the following:

  • Print something before you call Audit.find(), to assert that the background task is actually executing.
  • Try to ensure that the Audit.find() actually returns something.

But to answer your issue title: you can certainly use await in a background task, and it should work. My money would be on the Audit.find() doesn't return anything.

@leaguidi
Copy link
Author

leaguidi commented Sep 17, 2022 via email

@leaguidi
Copy link
Author

leaguidi commented Sep 17, 2022 via email

@Kludex
Copy link
Sponsor Collaborator

Kludex commented Sep 18, 2022

the code is correct now, sorry for my English.

There are people on our discord server that can help you in Spanish: https://fastapi.tiangolo.com/help-fastapi/?h=discord#join-the-chat.

@vanishingESCkey
Copy link

@leaguidi if you use BaseHTTPMiddleware in your project then it may affect your BackgroundTasks, take a look at issues mentioned in encode/starlette#1715 (comment)

@thomasleveil
Copy link

thomasleveil commented Oct 6, 2022

@leaguidi @vanishingESCkey a fix for encode/starlette#1715 (comment) has been released in https://github.com/encode/starlette/releases/tag/0.21.0

Watch PR #5471

KotaHv added a commit to KotaHv/simple-gh that referenced this issue Oct 21, 2022
Repository owner locked and limited conversation to collaborators Feb 28, 2023
@tiangolo tiangolo converted this issue into discussion #8387 Feb 28, 2023

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Projects
None yet
Development

No branches or pull requests

7 participants