Comments (14)
@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.
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.
@tiangolo thanks for the reply, I ended up adding more features to my project just to justify celery :D
from fastapi.
from fastapi.
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.
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.
Awesome! I'm glad to hear you like the design/interface.
from fastapi.
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.
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.
@outofnames I guess I would use celery in this scenario.
from fastapi.
Doesn't using celery only for sending emails seems overkill?
from fastapi.
@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.
@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.
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)
- "Behind a Proxy" changed behaviour in the new version 0.109.0 (in Uvicorn) HOT 13
- No streaming interface can not support concurrency for two fastapi servers
- Using pydantic Json Type as Form data type doesn't work HOT 1
- Raw docstring (leading `r`) defeats form feed `\f` truncation HOT 3
- OpenAPI Example with multipart/form-data not showing up HOT 5
- [BUG] Using Nested Pydantic models and `params: MyModel = Depends()` forces OpenAPI docs GET methods to require a request body. HOT 6
- How to fix this bug? HOT 2
- [BUG] Upgrade python-mulipart==0.0.7 from low version fastapi upload file may be 400 HOT 4
- Use `RootModel` as query parameter HOT 2
- Context managers in `Depends` are broken after 0.106 HOT 16
- Middleware runs twice HOT 8
- Support for Pydantic deprecated fields HOT 1
- axios can't receive error response status code
- Potential footgun when using custom `Response(background=<Task()>)` in conjunction with injected `BackgroundTasks` - the custom response overwrites the tasks HOT 3
- lifespan
- Breaking change with path parameters when updating to pydantic>=2 from pydantic<2 HOT 1
- trying to live video stream using Fastapi
- Package on test.pypi.org is broken
- middleware type
- It throws an exception when I specify return Http status code
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fastapi.