我编写了一个通用的dbhandler模块,它可以缠绕数据容器并将它们上传到mysql数据库,并且独立于db结构。现在我想添加一个默认值或将数据推入sqlite数据库的可能性。从结构上看,这与这个问题有关。程序包如下所示:
dbhandler\
dbhandler.py
models\
meta.py
default\
default_DB_map.py
default_DB.cfg
default.cfg是描述dbhandler脚本的数据库的配置文件。默认的\u db \u map.py包含db的每个表的Map,该表从基继承:
from sqlalchemy import BigInteger, Column, Integer, String, Float, DateTime
from sqlalchemy import Date, Enum
from ..meta import BASE
class db_info(BASE):
__tablename__ = "info"
id = Column(Integer, primary_key=True)
name = Column(String)
project = Column(String)
manufacturer = Column(String)
...
class db_probe(BASE):
__tablename__ = "probe"
probeid = Column(Integer, primary_key=True)
id = Column(Integer)
paraX = Column(String)
...
在meta.py中,我初始化声明性的\u基对象:
from sqlalchemy.ext.declarative import declarative_base
BASE = declarative_base()
最后,我在dbhandler.py中导入base并创建引擎和会话:
"DBHandler module"
...
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from models import meta #pylint: disable=E0401
....
class DBHandler(object):
"""Database handling
Methods:
- get_dict: returns table row
- add_item: adds dict to DB table
- get_table_keys: gets list of all DB table keys
- get_values: returns all values of key in DB table
- check_for_value: checks if value is in DB table or not
- upload: uploads data container to DB
- get_dbt: returns DBTable object
"""
def __init__(self, db_cfg=None):
"""Load credentials, DB structure and name of DB map from cfg file,
create DB session. Create DBTable object to get table names of DB
from cfg file, import table classes and get name of primary keys.
Args:
- db_cfg (yaml) : contains infos about DB structure and location
of DB credentials.
Misc:
- cred = {"host" : "...",
"database" : "...",
"user" : "...",
"passwd" : "..."}
"""
...
db_cfg = self.load_cfg(db_cfg)
if db_cfg["engine"] == "sqlite":
engine = sqlalchemy.create_engine("sqlite:///mySQlite.db")
meta.BASE.metadata.create_all(engine)
session = sessionmaker(bind=engine)
self.session = session()
elif db_cfg["engine"] == "mysql+mysqlconnector":
cred = self.load_cred(db_cfg["credentials"])
engine = sqlalchemy.create_engine(db_cfg["engine"]
+ "://"
+ cred["user"] + ":"
+ cred["passwd"] + "@"
+ cred["host"] + ":"
+ "3306" + "/"
+ cred["database"])
session = sessionmaker(bind=engine)
self.session = session()
else:
self.log.warning("Unkown engine in DB cfg...")
# here I'm importing the table classes stated in the config file
self.dbt = DBTable(map_file=db_cfg["map"],
table_dict=db_cfg["tables"],
cr_dict=db_cfg["cross-reference"])
很明显,我在“if db\u cfg[“engine”]=“sqlite”:“段落中做了一些错误的事情,但我不知道是什么。这个脚本与mysql引擎配合得很好。当我初始化dhandler对象时,我得到一个空的mysqlite.db文件。在该会话中添加一些内容将导致“(sqlite3.operationalerror)没有这样的表:info…”。但是,我可以在表对象上使用类似“sqlalchemy.inspect”的内容,而不会出现任何错误。所以我手头有正确的表对象,但它们不知怎么地没有连接到基?
1条答案
按热度按时间nukf8bse1#
对于sqlite,表类的导入似乎需要在创建db之前进行。
(通过pydoc.locate btw完成)必须在
被称为。我认为这并不重要,因为我进口基地在开始,因为它的工作只是罚款时,使用不同的引擎。