我正在尝试使用
Pydantic.BaseModel.model_dump()
但当我调用它时 AttributeError: type object 'BaseModel' has no attribute 'model_dump'
会加注。还尝试实例化 BaseModel
类。问题是 vscode 提示工具将其显示为可用的方法,当我使用 Pydantic.BaseModel.dict()
时,它会警告我应该使用 model_dump()
。
我正在使用Python 3.10.4
> pip freeze
annotated-types==0.6.0
anyio==3.7.1
exceptiongroup==1.1.3
fastapi==0.103.2
idna==3.4
pydantic==2.4.2
pydantic_core==2.10.1
sniffio==1.3.0
starlette==0.27.0
真正奇怪的是,当我在
pydantic.__version__
Web api 中执行 FastApi
时,它返回 v.1.10.2。这是怎么回事?
编辑:
from typing import Optional
from fastapi import FastAPI
from fastapi.params import Body
from pydantic import BaseModel
import pydantic
app = FastAPI()
class Post(BaseModel):
title: str
content: str
published: bool = True # default value
rating: Optional[int] = None
@app.post("/createpost")
def create_posts(new_post: Post):
print('>>>>', pydantic.__version__)
print(pydantic.BaseModel.model_dump()) # => raises the error
# print(new_post.model_dump()) # => raises the error
return {"data": "new_post"}
(fastapi-course) ➜ fastapi-course uvicorn main:app --reload
INFO: Will watch for changes in these directories: ['/home/juanc/Documents/fastapi-course']
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [76395] using WatchFiles
INFO: Started server process [76397]
INFO: Waiting for application startup.
INFO: Application startup complete.
'>>>>' 1.10.2
INFO: 127.0.0.1:40264 - "POST /createpost HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/juanc/.local/lib/python3.8/site-packages/uvicorn/protocols/http/httptools_impl.py", line 404, in run_asgi
result = await app( # type: ignore[func-returns-value]
File "/home/juanc/.local/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__
return await self.app(scope, receive, send)
File "/home/juanc/.local/lib/python3.8/site-packages/fastapi/applications.py", line 270, in __call__
await super().__call__(scope, receive, send)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/applications.py", line 124, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 184, in __call__
raise exc
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/middleware/errors.py", line 162, in __call__
await self.app(scope, receive, _send)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/middleware/exceptions.py", line 75, in __call__
raise exc
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/middleware/exceptions.py", line 64, in __call__
await self.app(scope, receive, sender)
File "/home/juanc/.local/lib/python3.8/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
raise e
File "/home/juanc/.local/lib/python3.8/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
await self.app(scope, receive, send)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/routing.py", line 680, in __call__
await route.handle(scope, receive, send)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/routing.py", line 275, in handle
await self.app(scope, receive, send)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/routing.py", line 65, in app
response = await func(request)
File "/home/juanc/.local/lib/python3.8/site-packages/fastapi/routing.py", line 231, in app
raw_response = await run_endpoint_function(
File "/home/juanc/.local/lib/python3.8/site-packages/fastapi/routing.py", line 162, in run_endpoint_function
return await run_in_threadpool(dependant.call, **values)
File "/home/juanc/.local/lib/python3.8/site-packages/starlette/concurrency.py", line 41, in run_in_threadpool
return await anyio.to_thread.run_sync(func, *args)
File "/home/juanc/.local/lib/python3.8/site-packages/anyio/to_thread.py", line 28, in run_sync
return await get_asynclib().run_sync_in_worker_thread(func, *args, cancellable=cancellable,
File "/home/juanc/.local/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 818, in run_sync_in_worker_thread
return await future
File "/home/juanc/.local/lib/python3.8/site-packages/anyio/_backends/_asyncio.py", line 754, in run
result = context.run(func, *args)
File "/home/juanc/Documents/fastapi-course/./main.py", line 26, in create_posts
print(pydantic.BaseModel.model_dump())
AttributeError: type object 'BaseModel' has no attribute 'model_dump'
您可能安装了两个版本的
pydantic
,因此运行conda list
和pip list
来检查pydantic版本。
这是怎么发生的?
我通过 pip 安装
pydantic==2.5.3
时遇到同样的错误,但是当我打印 pydantic.__version__
时,它显示 1.10.13
。所以我猜有些软件包可能需要pydantic==1.10.13
,并且它被自动安装了。
如何解决?
运行
pip unintall pydantic
TWICE,然后运行 pip install -U pydantic
。pydantic.__version__
,现在我们得到了正确版本的pydantic。