Creating background processes
The FastAPI framework is also capable of running background jobs as part of an API service execution. It can even run more than one job almost simultaneously without intervening in the main service execution. The class responsible for this is BackgroundTasks
, which is part of the fastapi
module. Conventionally, we declare this at the end of the parameter list of the API service method for the framework to inject the BackgroundTask
instance.
In our application, the task is to create audit logs of all API service executions and store them in an audit_log.txt
file. This operation is part of the background.py
script that is part of the main project folder, and the code is shown here:
from datetime import datetime def audit_log_transaction(touristId: str, message=""): with open("audit_log.txt", mode="a") as logfile: content = f"tourist {touristId...