【问题标题】:Return uppercase UUID in FastApi在 FastApi 中返回大写 UUID
【发布时间】:2022-07-15 17:09:30
【问题描述】:

在响应模型中使用带有 pydantic 模型的 FastApi 时,我发现 http 响应总是返回小写的 uuid。有什么标准方法可以将它们大写吗?

from fastapi import FastAPI
from pydantic import BaseModel
from uuid import UUID
app = FastAPI()

class Test(BaseModel):
    ID: UUID

@app.get("/test", response_model=Test)
async def test():
    id_ = uuid.uuid4()
    return Test(ID=id_)
   

发出请求时,返回的 uuid 将是小写的。

from requestr
a = requests.get("http://localhost:800/test").text # you ir
# a -> '{"ID":"fffc0b5b-8e8d-4d06-b910-2ae8d616166c"}' # it is lowercased

我发现将它们返回大写的唯一有点老套的方法是覆盖 uuid 类 __str__ 方法或子类化 uuid:

我尝试过的(并且有效):

# use in main.py when importing for first time
def newstr(self):
    hex = '%032x' % self.int
    return ('%s-%s-%s-%s-%s' % (hex[:8], hex[8:12], hex[12:16], hex[16:20], hex[20:])).upper()


uuid.UUID.__str__ = newstr

但我想知道是否有在不修改原始类的情况下执行此操作的标准方法,可能是 pydantic 中的后期处理或 FastApi 中的设置。

【问题讨论】:

    标签: python request fastapi uuid


    【解决方案1】:

    您可以自定义json_encoders:

    class Test(BaseModel):
        ID: UUID
    
        class Config:
            json_encoders = {
                UUID: lambda val: str(val).upper()
            }
    

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多