gpt4 book ai didi

python - 从类访问 SQLalchemy

转载 作者:太空宇宙 更新时间:2023-11-04 03:49:32 28 4
gpt4 key购买 nike

我正在做一个项目,我需要创建一个类实例,该实例具有连接到数据库并从中获取数据的方法(我使用 SQLite 作为后端)。我有一些使用 flask-sqlalchemy 的经​​验,但是当涉及到纯 SQLAlchemy 时我迷路了。概念如下:用户创建 DataSet 的实例,并将路径作为 __init__ 参数传递给数据库。如果数据库已经存在,我只想连接到它并进行查询,如果不存在,我想使用模型创建一个新数据库。但我不明白该怎么做。

这是 DataSet 代码:

from os.path import normcase, split, join, isfile
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
import errors
import trainset
import testset


class DataSet:
def __init__(self, path_to_set, path_to_db, train_set=False, path_to_labels=None, label_dict=None,
custom_name=None):
self.__path_to_set = path_to_set
self.__label_dict = label_dict

if custom_name is None:
dbpath = join(path_to_db, 'train.db')
if train_set is False:
dbpath = join(path_to_db, 'test.db')
else:
dbpath = join(path_to_db, custom_name)
if isfile(dbpath):
self.__prepopulated = True
else:
self.__prepopulated = False
self.__dbpath = dbpath

if train_set is True and path_to_labels is None:
raise errors.InsufficientData('labels', 'specified')
if train_set is True and not isfile(path_to_labels):
raise errors.InsufficientData('labels', 'found at specified path', path_to_labels)

def prepopulate(self):
engine = create_engine('sqlite:////' + self.__dbpath)
self.__prepopulated = True

这是trainset代码:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, PickleType, Integer, MetaData

Base = declarative_base()
metadata = MetaData()


class TrainSet(Base):
__tablename__ = 'train set'
id = Column(Integer, primary_key=True)
real_id = Column(String(60))
path = Column(String(120))
labels = Column(PickleType)
features = Column(PickleType)

这是测试集代码:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, PickleType, Integer, MetaData

Base = declarative_base()
metadata = MetaData()


class TestSet(Base):
__tablename__ = 'test set'
id = Column(Integer, primary_key=True)
real_id = Column(String(60))
path = Column(String(120))
features = Column(PickleType)

因此,如果用户在创建 DataSet 实例时传递了 train_set=True,我想使用 TrainSet 模型创建数据库, 否则创建一个 TestSet 数据库。我希望这发生在 prepopulate 方法中,但是,我不知道该怎么做 - 文档要求这样做:Base.metadata.create_all(engine),但我不知道将这段代码放在哪里。

最佳答案

首先保存参数train_set:

class DataSet:
def __init__(self, path_to_set, path_to_db, train_set=False, path_to_labels=None, label_dict=None,
custom_name=None):
self._train_set = train_set
# ...

然后,在 prepopulate 中使用它来创建合适的模型:

def prepopulate(self):
engine = create_engine('sqlite:////' + self.__dbpath)
if self._train_set:
trainset.Base.create_all(engine)
else:
testset.Base.create_all(engine)
self.__prepopulated = True

还有一件事:不要在您的“私有(private)”变量前加上双下划线。请阅读PEP 8 -- Style Guide for Python Code供引用。

关于python - 从类访问 SQLalchemy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21967536/

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