FastAPI python: How to run a thread in the background?

Option 1 You should start your Thread before calling uvicorn.run, as uvicorn.run is blocking the thread. import time import threading from fastapi import FastAPI import uvicorn app = FastAPI() class BackgroundTasks(threading.Thread): def run(self,*args,**kwargs): while True: print(‘Hello’) time.sleep(5) if __name__ == ‘__main__’: t = BackgroundTasks() t.start() uvicorn.run(app, host=”0.0.0.0″, port=8000) You could also start your thread using … Read more

How to do multiprocessing in FastAPI

async def endpoint You could use loop.run_in_executor with ProcessPoolExecutor to start function at a separate process. @app.post(“/async-endpoint”) async def test_endpoint(): loop = asyncio.get_event_loop() with concurrent.futures.ProcessPoolExecutor() as pool: result = await loop.run_in_executor(pool, cpu_bound_func) # wait result def endpoint Since def endpoints are run implicitly in a separate thread, you can use the full power of modules … Read more

How do I get my FastAPI application’s console log in JSON format with a different structure and different fields?

You could do that by creating a custom Formatter using the built-in logger module. You can use the extra parameter when logging messages to pass contextual information, such as url and headers. Python’s JSON module already implements pretty-printing JSON data in the dump() function, using the indent parameter that allows you to define the indent … Read more