返回fastapi中的大写UUID

发布于 2025-02-06 05:08:00 字数 954 浏览 3 评论 0原文

当将FastApi与Repons响应模型的Pydantic模型一起使用时,我发现uuid始终通过HTTP响应返回小写。是否有任何标准方法可以将它们退回上层?

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 __ 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中的设置。

When using FastApi with a pydantic model at the reponse model, I found that the uuid are always returned lowercase by the http response. Is there any standard way to return them upper cased?

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_)
   

When making the request the returned uuid will be in lowercased.

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

The only somewhat hacky way I found to return them uppercased is overwriting the uuid class __str__ method or sub-classing uuid:

What I tried (and works):

# 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

But I was wondering if there is a standard way of doing this without modifying the original class, maybe a post process in pydantic or a setting in FastApi.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

终陌 2025-02-13 05:08:00

您可以定义自定义json_encoders

class Test(BaseModel):
    ID: UUID

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

You can define custom json_encoders:

class Test(BaseModel):
    ID: UUID

    class Config:
        json_encoders = {
            UUID: lambda val: str(val).upper()
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文