我有很多使用post_init嵌套的数据类
from dataclasses import dataclass
from typing import List
from typing import Optional
from typing import Union
@dataclass
class MyClass:
signed_key: str
signature: str
@dataclass
class Message:
signature: str
my_class: Union[MyClass, dict]
protocol_version: str
signed_message: str
def __post_init__(self):
self.my_class = MyClass(**self.my_class)
Run Code Online (Sandbox Code Playgroud)
它工作得很好,但问题是,如果我想将 Message 转换为 dict,如下所示:
#create a message object before
print(message.__dict__)
Run Code Online (Sandbox Code Playgroud)
我得到的输出:
{'signature': 'test', 'my_class': Myclass(signed_key='test', signature='test'), 'protocol_version': 'test', 'signed_message': 'test'}
Run Code Online (Sandbox Code Playgroud)
我想要什么(嵌套字典):
{'signature': 'test', 'my_class': {'signed_key': 'test', 'signature': 'test'}, 'protocol_version': 'test', 'signed_message': 'test'}
Run Code Online (Sandbox Code Playgroud)
我可以使用像 attrs 或 pydantic 这样的库,但这里的目标是只使用纯 python
如何在FastAPI中将字符串转换为模型类型?如果我有学生模型并且想要将字符串学生转换为类型模型。如何转换呢?
engine = create_engine(SQLALCHAMY_DATABASE_URL,pool_pre_ping=True,pool_recycle=3600)
meta = MetaData()
con = engine.connect()
SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
Base = declarative_base()
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def convert_model(student,db:Session = Depends(database.get_db)):
Q=student.all()
convert_model(student,db)
Run Code Online (Sandbox Code Playgroud)
它给出了错误str object has no attribute all()