我正在尝试导入 python 程序的 Lightning 包,但不断收到此错误消息:无法从 'pydantic.main' (c:\Users\mt767\AppData\Local\Programs\Python\Python310 导入名称 'ModelMetaclass' \lib\site-packages\pydantic\main.py)。
我已检查 pydantic 软件包是否是最新的,并尝试卸载并重新安装它。我在网上找到的解决方案都不起作用。代码只是简单地导入lightning包:
import lightning
我正在从 Pydantic v1 迁移到 v2,并尝试将已弃用 @validator的所有用途替换为@field_validator.
但是,我之前使用过pre 验证器参数,在转到 后@field_validator,我收到以下错误:
TypeError: field_validator() got an unexpected keyword argument 'pre'
Run Code Online (Sandbox Code Playgroud)
V2 中是否也已弃用 pre 的使用?尽管有页面顶部警告,但V2 验证器文档中似乎仍然引用了它:
此页面仍需要更新 v2.0。
希望其他人已经解决了这个问题并可以提出最佳的前进路线。谢谢!
.dict()当我在 FastAPI 中的 Pydantic 模型上使用方法时,它会给我一个弃用警告。我pydantic通过命令行升级,但仍然显示相同的错误。我也更新了 VScode,但同样的问题。
python deprecation-warning visual-studio-code pydantic fastapi
我想实例化一个打字Union来源于两类pydantic.BaseModel直接。但是我得到了一个TypeError: Cannot instantiate typing.Union.
我见过的所有示例都声明Union为类的属性(例如此处)。
以下是我想使用的最小示例。
from pydantic import BaseModel
from typing import Union
class A(BaseModel):
a: int
class B(A):
b: int
class C(A):
c: str
MyUnion = Union[B, C, A]
mu = MyUnion(a=666, c='foo') # This command throws the TypeError
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这一目标?
这是我得到的错误
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-40-8163e3490185> in <module>
----> 1 MyUnion()
c:\program files\python37\lib\typing.py in __call__(self, *args, **kwargs)
668 raise TypeError(f"Type {self._name} cannot be instantiated; …Run Code Online (Sandbox Code Playgroud) 我尝试按如下方式使用 Pydantic:
from pydantic import BaseModel
class A(BaseModel):
prop1: str
prop2: str
class B(BaseModel):
a: A
data = {
'prop1': 'some value',
'prop2': 'some other value'
}
b = B(**data)
Run Code Online (Sandbox Code Playgroud)
这给了我以下错误:
Traceback (most recent call last):
File "main.py", line 18, in <module>
b = B(**data)
File "pydantic/main.py", line 283, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for B
a
field required (type=value_error.missing)
Run Code Online (Sandbox Code Playgroud)
pydantic 是否可以创建所需的A实例B?
I have recently come to know about fastAPI and worked my way through the tutorial and other docs. Although fastAPI is pretty well documented, I couldn't find information about how to process a nested input when working with a database.
For testing, I wrote a very small family API with two models:
class Member(Base):
__tablename__ = 'members'
id = Column(Integer, primary_key=True, server_default=text("nextval('members_id_seq'::regclass)"))
name = Column(String(128), nullable=False)
age = Column(Integer, nullable=True)
family_id = Column(Integer, ForeignKey('families.id', deferrable=True, initially='DEFERRED'), nullable=False, index=True)
family = …Run Code Online (Sandbox Code Playgroud) 我在 Kubuntu 18.04 上安装了python3 3.6.9。我已经安装了fastapi使用pip3 install fastapi。我正在尝试通过其官方文档测试驱动该框架,并且我在其指南的关系数据库部分。
在schemas.py:
from typing import List
from pydantic import BaseModel
class VerseBase(BaseModel):
AyahText: str
NormalText: str
class Verse(VerseBase):
id: int
class Config:
orm_mode = True
Run Code Online (Sandbox Code Playgroud)
VS代码突出一个错误from pydantic import BaseModel,它会告诉:No name 'BaseModel' in module 'pydantic'。此外,当我尝试运行时,出现uvicorn main:app reload 以下错误:
Run Code Online (Sandbox Code Playgroud)File "./main.py", line 6, in <module> from . import crud, models, schemas ImportError: attempted relative import with no known parent package
我试图renstallpydantic …
以下代码接收一些已 POST 到 FastAPI 服务器的 JSON。FastAPI 使其可以作为 Pydantic 模型在函数中使用。我的示例代码通过写入文件来处理它。我不喜欢的(这似乎是使用 Pydantic List 的副作用)是我必须循环回来才能获得一些可用的 JSON。
我怎样才能在不循环的情况下做到这一点?
我觉得这一定是可能的,因为return images它确实有效。
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
import json
app = FastAPI()
class Image(BaseModel):
url: str
name: str
@app.post("/images/multiple/")
async def create_multiple_images(images: List[Image]):
#return images # returns json string
#print(images) # prints an Image object
#print(images.json()) # AttributeError: 'list' object has no attribute 'json'
#print(json.dumps(images)) # TypeError: Object of type Image is not JSON serializable
img_data = …Run Code Online (Sandbox Code Playgroud) 具体来说,我希望以下示例能够正常工作:
from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
class DataConfiguration(BaseModel):
textColumnNames: List[str]
idColumn: str
@app.post("/data")
async def data(dataConfiguration: DataConfiguration,
csvFile: UploadFile = File(...)):
pass
# read requested id and text columns from csvFile
Run Code Online (Sandbox Code Playgroud)
如果这不是 POST 请求的正确方法,请告诉我如何从 FastAPI 中上传的 CSV 文件中选择所需的列。
我试图返回 Company 类型的对象列表,仅包括“已批准”的对象,并且具有或多或少的属性,具体取决于请求列表的用户是超级用户还是普通用户。到目前为止,这是我的代码:
@router.get("/", response_model=List[schema.CompanyRegularUsers])
def get_companies(db: Session = Depends(get_db), is_superuser: bool = Depends(check_is_superuser)):
"""
If SU, also include sensitive data.
"""
if is_superuser:
return crud.get_companies_admin(db=db)
return crud.get_companies_user(db=db)
#
Run Code Online (Sandbox Code Playgroud)
该函数根据请求正确返回对象(即,仅is_approved=True公司如果是常规请求,并且两者is_approved=True都由is_approved=False超级用户请求。问题是,两种情况都使用schema.CompanyRegularUsers,并且我想schema.CompanySuperusers在 SU 发出请求时使用。
我怎样才能实现这个功能?即,有没有办法有条件地设置response_model装饰器函数的属性?
我尝试过使用JSONResponse和调用 Pydantic's schema.CompanySuperusers.from_orm(),但它不适用于公司列表......
pydantic ×10
python ×9
fastapi ×6
python-3.x ×2
http ×1
http-post ×1
import ×1
importerror ×1
json ×1
orm ×1
python-3.8 ×1
sqlalchemy ×1
typing ×1