返回fastapi中的大写UUID
当将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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以定义自定义
json_encoders
:You can define custom
json_encoders
: