Search code examples
pythonpython-3.xloggingfastapiuuid

How to generate uuid for each FastAPI request in a multiprocessing-safe way


I'm building logging process for my API. For each request I wish to have unique ID and save this id with some other metadata.

I've come up with using uuid.uuid5() as my request_id generator, but now I need to do this in a multiprocessing-safe way (see https://docs.python.org/3/library/uuid.html).

Is there a solution for this?

P.S., my current solution is something like that:

@app.get("/search/", dependencies=[Depends(HTTPBearer())])
@authentication
async def search(
        request: Request,
        response: Response,
        #some more params here
) -> dict:
        #do actual computation
        ...
        request_id = uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
        #insert request_id to DB with other log info and add in to response json
        ...
        return result

Solution

  • You can try this:

    import os
    import random
    import uuid
    
    uuid.uuid5(uuid.NAMESPACE_DNS, f'{uuid.uuid1()}{random.random()}{os.getpid()}').hex