gpt4 book ai didi

python - sqlalchemy : how can i map an existing class without modifying it?

转载 作者:行者123 更新时间:2023-12-02 02:54:04 28 4
gpt4 key购买 nike

我有一定数量的 python 类,我想使用 python sqlalchemy 将它们映射到数据库中的表。我看到了映射类派生自 sqlalchemy 基类的示例。我不想那样做。还有其他办法吗?

例如,如何映射这个简单的类?

class Person:
def __init__(self, firstname: str = "x", name: str = "y", age: int = 0):
self.firstname = firstname
self.name = name
self.age = age

def __str__(self) -> str:
return f"[{self.__firstname},{self.__name},{self.__age}]"

@property
def id(self):
return self.__id

@property
def firstname(self) -> str:
return self.__firstname

@property
def name(self) -> str:
return self.__name

@property
def age(self) -> int:
return self.__age

# setters

@id.setter
def id(self, id: int):
if not isinstance(id,int) or id<=0:
raise MyException(f"...")

@firstname.setter
def firstname(self, firstname: str):
if Utils.is_string_ok(firstname):
self.__firstname = firstname.strip()
else:
raise MyException("...")

@name.setter
def name(self, name: str):
if Utils.is_string_ok(name):
self.__name = name.strip()
else:
raise MyException("...")

@age.setter
def age(self, age: int):
error = False
if isinstance(age, int):
if age >= 0:
self.__age = age
else:
error = True
else:
error = True
if error:
raise MyException("...")

我想将其映射到一个包含列(col1、col2、col3、col4)的表(例如与类属性不同的任意名称)。

最佳答案

对于任何感兴趣的人,我终于明白了(下面我更改了工作代码的标识符以匹配原始帖子):

# imports
from sqlalchemy import create_engine, Table, Column, Integer, String, MetaData
from sqlalchemy.orm import mapper, sessionmaker

from Person import Person

# mysql database
engine = create_engine("mysql+mysqlconnector://root@localhost/dbpersonnes")

# metadata
metadata = MetaData()

# table
persons_table = Table("persons", metadata,
Column('col1', Integer, primary_key=True),
Column('col2', String(30), nullable=False),
Column("col3", String(30), nullable=False),
Column("col4", Integer, nullable=False)
)

# mapping
mapper(Person, persons_table, properties={
'id': persons_table.c.col1,
'firstname': persons_table.c.col2,
'name': persons_table.c.col3,
'age': persons_table.c.col4,
})

# session factory
Session = sessionmaker()
Session.configure(bind=engine)

# session
session = Session()

# insert
session.add(Personne(67, "x", "y", 10))
session.commit()

# query
personnes = session.query(Personne).all()

# logs
for personne in personnes:
print(personne)

关于python - sqlalchemy : how can i map an existing class without modifying it?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61458069/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com