Code Monkey home page Code Monkey logo

Comments (14)

tiangolo avatar tiangolo commented on April 28, 2024 3

@madkote if your processing is in an async function (let's say, created with async def process_something(): ...), you can use an async function for your path operation too, and inside of it, use await process_something().

from starlette.concurrency import run_in_threadpool

@app.get("/items"/)
async def read_items():
    result = await process_something("argument 1", keyword_arg2="keyword argument")
    return result

If it's a normal function, you can use run_in_threadpool from Starlette, pass your standard function and await it, something like:

from starlette.concurrency import run_in_threadpool

@app.get("/items"/)
async def read_items():
    result = await run_in_threadpool(process_something, "argument 1", keyword_arg2="keyword argument")
    return result

If that doesn't solve your problem, please create a new issue for it so we can continue the discussion there.


As the original issue should be solved now with the support for BackgroundTasks, I'll close it now. But feel free to add more comments or create new issues.

from fastapi.

wshayes avatar wshayes commented on April 28, 2024 2

Wow - that's a lot more intuitive and will avoid the - "it's not working because you didn't return the JSONResponse()" issue from Starlette - thank you!

from fastapi.

outofnames avatar outofnames commented on April 28, 2024 2

@tiangolo thanks for the reply, I ended up adding more features to my project just to justify celery :D

from fastapi.

euri10 avatar euri10 commented on April 28, 2024

from fastapi.

wshayes avatar wshayes commented on April 28, 2024

You can already do this since it's built on Starlette - make sure you return JSONResponse() otherwise it won't start the background tasks.

Example:

from starlette.background import BackgroundTasks
from starlette.responses import UJSONResponse, JSONResponse

@router.post("/nanopubs/flushtosearch", tags=["Nanopubs"])
def flushtosearch():
    """
    Flush all nanopubs to search endpoint
    """

    tasks = BackgroundTasks()
    tasks.add_task(services.search.elasticsearch_index_all_nanopubs)

    message = "Reset Index and Flush to search submitted"
    return JSONResponse(message, background=tasks)

from fastapi.

tiangolo avatar tiangolo commented on April 28, 2024

Again, thanks for your help here guys @euri10 and @wshayes !

It is now integrated into FastAPI in a (probably) more intuitive way (in version 0.10.0).

The new docs are here: 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 April 28, 2024

Awesome! I'm glad to hear you like the design/interface.

from fastapi.

madkote avatar madkote commented on April 28, 2024

hi all, one similar question:

  • let assume I would like to have a background task, which should NOT be executed after the response has been sent. but before?
  • e.g. in REST, I receive the first chunk of data (multipart/form-data) and would like to start process it in background (e.g. thread - since it is blocking). After a final chunk, I would to await for the result from the executor and return the response to the client.

Is it possible with fastapi?

from fastapi.

outofnames avatar outofnames commented on April 28, 2024

Hi!
Is it possible to use BackgroundTasks before HTTPException?
I have a scenario in which I need to send a email when an exception occurs, but BackgroundTasks doesn't seem to work when a HTTPException is raised

from fastapi.

madkote avatar madkote commented on April 28, 2024

@outofnames I guess I would use celery in this scenario.

from fastapi.

outofnames avatar outofnames commented on April 28, 2024

Doesn't using celery only for sending emails seems overkill?

from fastapi.

madkote avatar madkote commented on April 28, 2024

@outofnames well, otherwise you would need to extend HttpExceptino to be able to run background tasks, which might be difficult. Maybe, additionally, I would ask at starlette project directly.
If you find a solution, please share - I would very appreciate that!

from fastapi.

tiangolo avatar tiangolo commented on April 28, 2024

@outofnames you can probably also use asyncio.ensure_future(awaitable_send_email()) inside of the exception handler, without needing to plug a background task.

https://docs.python.org/3/library/asyncio-future.html#asyncio.ensure_future

from fastapi.

github-actions avatar github-actions commented on April 28, 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.