Giter Site home page Giter Site logo

Comments (5)

euri10 avatar euri10 commented on May 5, 2024

afaik you have to explicitly use a JSONResponse, but @tiangolo might have a way better view on this.

I was unable to find a way to pass the background kwargs to a FastAPI Response without it.

here's a working example shamelessly adapted from the starlette test cases

def test_multiple_tasks2():

    TASK_COUNTER = 0
    def increment(amount):
        nonlocal TASK_COUNTER
        TASK_COUNTER += amount
    app = FastAPI()

    @app.get("/")
    async def root():
        tasks = BackgroundTasks()
        tasks.add_task(increment, amount=1)
        tasks.add_task(increment, amount=2)
        tasks.add_task(increment, amount=3)
        message = {'status': 'successful'}
        return JSONResponse(message, background=tasks)

    client = TestClient(app)
    response = client.get("/")
    assert response.json() == {'status': 'successful'}
    assert TASK_COUNTER == 1 + 2 + 3

from fastapi.

wshayes avatar wshayes commented on May 5, 2024

Yes - this works, and to reinforce the warning above - if you don't return JSONResponse with the background=tasks parameter - it won't initiate the background tasks.

from fastapi.

tiangolo avatar tiangolo commented on May 5, 2024

Thanks for your help here guys @euri10 and @wshayes !

It is now integrated into FastAPI in a more simple way, similarly to when using the Request object directly, just declare a function parameter of type BackgroundTasks and add tasks to it directly. The rest is handled by FastAPI. And now you don't have to return a JSONResponse directly.

Here are the new docs: https://fastapi.tiangolo.com/tutorial/background-tasks/

In short:

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def write_notification(email: str, message=""):
    with open("log.txt", mode="w") as email_file:
        content = f"notification for {email}: {message}"
        email_file.write(content)


@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"}

from fastapi.

tiangolo avatar tiangolo commented on May 5, 2024

As this is now solved, I'll close this issue. But feel free to add more comments or create new issues.

from fastapi.

github-actions avatar github-actions commented on May 5, 2024

Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

from fastapi.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.