I have a FastAPI app with an end point that may have to do a long computation. As a replacement of the actual code let me use this mock example, in which I am trying to keep the features that I think are relevant.
from fastapi import FastAPI
from fastapi.responses import JSONResponse
import subprocess
app = FastAPI()
@app.put("/expensive")
def expensive():
command = "for x in $(seq 1 10000); do echo ${x}; done"
subprocess.run(command, shell=True, check=True)
return JSONResponse(content=True)
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"deleteme:app",
host='0.0.0.0',
port=12345,
reload=True
)
As in the mock example, the actual code run a third party software that does a computation that could, in some cases, take a long time.
When I send, with Postman, a PUT request, the app will start printing the natural numbers from 1 to 10000. I can cancel the request in Postman. However, the computation in the app will continue.
Question: I would like the user to be able to have a mechanism to cancel a specific request made to http://0.0.0.0:12345/expensive. What are ways to do this?
My lack of experience with Web APIs also causes that I am not finding the right key words to search about the subject. For example, combinations of fastapi request abort, or web api request cancel, don't seem to lead to posts discussing this topic.
A mechanism that I can think about could be:
- Send in the initial request an ID
request_id. - When the third party software is run, get its PID and store the key:value pair
request_id:PID. - Have a second end point to receive cancel requests. The user would submit the
request_idof the request that they would like to cancel. - Use the
request_idto then kill the subprocess with the corresponding PID.
This seem convoluted.