Home > Mobile >  How to spin-up a background process that doesn't close after a response is served in FastAPI
How to spin-up a background process that doesn't close after a response is served in FastAPI

Time:03-19

I'm writing a web hook server to receive updates when my git repository is pushed. Upon receiving the POST request from GitHub, I execute several commands like git pull, mvn install which take a very long time.
But the web hook request sent by GitHub timeouts after 10 seconds.
My code:

import logging
import os

from fastapi import FastAPI

app = FastAPI()
logger = logging.getLogger("uvicorn")


def exec_cmd(command):
    out = os.system(command)
    logger.info(str(out))


@app.post('/')
def func():
    logger.info("WebHook received")
    exec_cmd("git pull")
    exec_cmd("mvn clean install")
    exec_cmd("killall java")
    return {}


if __name__ == "__main__":
    import uvicorn

    exec_cmd("git pull")
    uvicorn.run("main:app", debug=False, reload=False, host="0.0.0.0")

Therefore I want to run the long running tasks in the background, and respond to GitHub's request as soon as possible.

How can I do this?
(If I make the exec_cmd() function async, when the request returns, the exec_cmd() function doesn't run till completion. )

CodePudding user response:

They are called BackgroundTasks in FastAPI and can be used by adding a BackgroundTasks type to your view function signature.

The example given in the documentation can be further adapter to your needs:

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()


def process_repository(email: str, message=""):
    exec_cmd("git pull")
    exec_cmd("mvn clean install")
    exec_cmd("killall java")


@app.post("/")
async def update_repository(background_tasks: BackgroundTasks):
    background_tasks.add_task(process_repository)
    return {"message": "Repository update has begun"}

Since you don't check the results this should work for your use case.

  • Related