-
Hi! I'm trying to port this code to lambda using lambda web adapter. @router.post("/node/", response_model=NodeCreateResponse, status_code=201)
async def create_node_endpoint(background_tasks: BackgroundTasks, node_data: NodeInfoPayload = Body(...)):
try:
node =await crud.create_node(node_data.payload)
background_tasks.add_task(crud.create_connections, node)
return JSONResponse(content={"payload":{"id":node.uid,"name":node.name}}, status_code=201)
except HTTPException as e:
raise e
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=400) After the return function the lambda is finished so the background tasks is never executed. I assume that this not is supported ¿there is any other options without change too much the source code? |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments
-
Lambda freezes the execution environment after the handler function returns. So the backup jobs won't work. However, you should be able to get around that with an internal extension. Lambda will wait until the internal extension finishes before freezing the execution environment. It is a good experiment to create a package to integrate FastAPI background tasks with Lambda internal extension. |
Beta Was this translation helpful? Give feedback.
-
"Lambda internal extension" But I'm not sure if is the correct way (it's a 2 years old repo). |
Beta Was this translation helpful? Give feedback.
-
That uses a wrapper script, which is not useful in this case. Let me create an example for this. |
Beta Was this translation helpful? Give feedback.
-
Before I complete the example, you can check out this Rust Lambda example: https://github.com/awslabs/aws-lambda-rust-runtime/tree/main/examples/extension-internal-flush |
Beta Was this translation helpful? Give feedback.
-
PR is created: #408 |
Beta Was this translation helpful? Give feedback.
-
The example is here: https://github.com/awslabs/aws-lambda-web-adapter/tree/main/examples/fastapi-background-tasks |
Beta Was this translation helpful? Give feedback.
The example is here: https://github.com/awslabs/aws-lambda-web-adapter/tree/main/examples/fastapi-background-tasks