![](/img/trans.png)
[英]How to generate a UUID field with FastAPI, SQLalchemy, and SQLModel
[英]How to generate uuid for each FastAPI request in a multiprocessing-safe way
我正在為我的 API 構建日志記錄過程。 對於每個請求,我希望擁有唯一的 ID 並將此 ID 與其他一些元數據一起保存。
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 ) .
有解決方案嗎?
PS,我目前的解決方案是這樣的:
@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
你可以試試這個:
import os
import random
import uuid
uuid.uuid5(uuid.NAMESPACE_DNS, f'{uuid.uuid1()}{random.random()}{os.getpid()}').hex
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.