继承BaseModel 报错AttributeError: __
2022-01-17 本文已影响0人
RedB
Bug经历
最近在写FastAPI的登录与注册,想要基于ResponseBody,派生出SuccessResponseBody和ErrorResponseBody。于是写了这么一段代码:
# schemas.py
class RespBody(BaseModel):
code: int
data: Optional[dict]
msg: Optional[str]
class SuccessRespBody(RespBody):
def __init__(self, data: dict):
self.code = 0
self.data = data
# main.py
@app.post("/token", response_model=RespBody)
def login_for_access_token(...):
....
return SuccessRespBody({"access_token":access_token})
结果报了错AttributeError: __fields_set__
解决办法
经过大佬的指点,最终找到了官方文档里,BaseModel继承的写法:https://pydantic-docs.helpmanual.io/usage/models/#model-signature
正确代码如下:
class RespBody(BaseModel):
code: int
data: Optional[dict]
msg: Optional[str]
class SuccessRespBody(RespBody):
def __init__(self, data: dict):
# super().__init__()如果不调用,父类的__init__就不会被调用,就会出错
super().__init__(code = 0, data = data)