У меня есть пакет, который устанавливает и размещает несколько соединений с различными базами данных. Однако не все эти базы данных существуют повсеместно. Кажется, когда я импортирую соединение с базой данных для БД, которого у меня нет, он не может правильно соединиться. Но затем, когда я импортирую второе хорошее соединение, мой сеанс базы данных прерывается.
Это импортирует соединение с БД, которого у меня нет локально. Connected = False, нет ни движка, ни Session, а у меня есть уникальная sqlalchemy Model Base.
from db.sqlalchemy.archive import database as adb, sas
print(adb)
<ArchiveDatabaseConnection (dbname='archive_20200302', profile='local', connected=False)>
print(adb.engine)
None
print(adb.Session)
None
print(adb.bases)
[sdssdb.sqlalchemy.archive.sas.Base]
Когда я импортирую соединение, работающее локально, и пытаюсь что-то запросить, оно завершается с непрозрачной ошибкой. Он подключен к БД, есть механизм и Сессия, а база данных сопоставлена с другим набором Модельных Баз.
from db.sqlalchemy.mangadb import database as mangadb, datadb
print(mangadb)
<MANGAdbDatabaseConnection (dbname='manga', profile='local', connected=True)>
print(mangadb.engine)
Engine(postgresql+psycopg2:///manga)
print(mangadb.Session)
<sqlalchemy.orm.scoping.scoped_session object at 0x11ea4b4e0>
print(mangadb.bases)
[<class 'db.sqlalchemy.mangadb.sampledb.Base'>, <class 'db.sqlalchemy.mangadb.datadb.Base'>]
session = mangadb.Session()
session.query(datadb.Cube).first()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/util/_collections.py in __getattr__(self, key)
209 try:
--> 210 return self._data[key]
211 except KeyError:
KeyError: 'type'
During handling of the above exception, another exception occurred:
AttributeError Traceback (most recent call last)
<ipython-input-15-5f15a5829806> in <module>
----> 1 session.query(datadb.Cube).first()
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/session.py in query(self, *entities, **kwargs)
1551 :class:`.Session`."""
1552
-> 1553 return self._query_cls(entities, self, **kwargs)
1554
1555 @property
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in __init__(self, entities, session)
189 self.session = session
190 self._polymorphic_adapters = {}
--> 191 self._set_entities(entities)
192
193 def _set_entities(self, entities, entity_wrapper=None):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in _set_entities(self, entities, entity_wrapper)
217 entity_wrapper(self, ent)
218
--> 219 self._set_entity_selectables(self._entities)
220
221 def _set_entity_selectables(self, entities):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in _set_entity_selectables(self, entities)
248
249 d[entity] = (ext_info, aliased_adapter)
--> 250 ent.setup_entity(*d[entity])
251
252 def _mapper_loads_polymorphically_with(self, mapper, adapter):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in setup_entity(self, ext_info, aliased_adapter)
4169 self.selectable = ext_info.selectable
4170 self.is_aliased_class = ext_info.is_aliased_class
-> 4171 self._with_polymorphic = ext_info.with_polymorphic_mappers
4172 self._polymorphic_discriminator = ext_info.polymorphic_on
4173 self.entity_zero = ext_info
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py in __get__(self, obj, cls)
853 if obj is None:
854 return self
--> 855 obj.__dict__[self.__name__] = result = self.fget(obj)
856 return result
857
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/mapper.py in _with_polymorphic_mappers(self)
2133 def _with_polymorphic_mappers(self):
2134 if Mapper._new_mappers:
-> 2135 configure_mappers()
2136 if not self.with_polymorphic:
2137 return []
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/mapper.py in configure_mappers()
3218 has_skip = False
3219
-> 3220 Mapper.dispatch._for_class(Mapper).before_configured()
3221 # initialize properties on all mappers
3222 # note that _mapper_registry is unordered, which
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/event/attr.py in __call__(self, *args, **kw)
259
260 for fn in self.parent_listeners:
--> 261 fn(*args, **kw)
262
263 def __len__(self):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/events.py in wrap(*arg, **kw)
644 arg[target_index] = arg[target_index].obj()
645 if not retval:
--> 646 fn(*arg, **kw)
647 return interfaces.EXT_CONTINUE
648 else:
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py in before_configured()
210 @event.listens_for(mapper, "before_configured")
211 def before_configured():
--> 212 self.cls.__declare_first__()
213
214 def _scan_attributes(self):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/api.py in __declare_first__(cls)
617 @classmethod
618 def __declare_first__(cls):
--> 619 cls._sa_decl_prepare_nocascade()
620
621 @classmethod
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/api.py in _sa_decl_prepare_nocascade(cls)
662 to_map.mapper_args_fn = mapper_args
663
--> 664 m = to_map.map()
665
666 for scls in cls.__subclasses__():
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py in map(self)
763 def map(self):
764 self._configs.pop(self._cls, None)
--> 765 return super(_DeferredMapperConfig, self).map()
766
767
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py in map(self)
685
686 def map(self):
--> 687 self._prepare_mapper_arguments()
688 if hasattr(self.cls, "__mapper_cls__"):
689 mapper_cls = util.unbound_method_to_callable(
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py in _prepare_mapper_arguments(self)
627 properties = self.properties
628 if self.mapper_args_fn:
--> 629 mapper_args = self.mapper_args_fn()
630 else:
631 mapper_args = {}
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/api.py in mapper_args()
657 def mapper_args():
658 args = m_args()
--> 659 args["polymorphic_on"] = pjoin.c.type
660 return args
661
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/util/_collections.py in __getattr__(self, key)
210 return self._data[key]
211 except KeyError:
--> 212 raise AttributeError(key)
213
214 def __contains__(self, key):
AttributeError: type
Если я попробую второй тип, я получу ошибку weakref
на DeclarativeMeta
.
session.query(datadb.Cube).first()
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-7-5f15a5829806> in <module>
----> 1 session.query(datadb.Cube).first()
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/session.py in query(self, *entities, **kwargs)
1551 :class:`.Session`."""
1552
-> 1553 return self._query_cls(entities, self, **kwargs)
1554
1555 @property
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in __init__(self, entities, session)
189 self.session = session
190 self._polymorphic_adapters = {}
--> 191 self._set_entities(entities)
192
193 def _set_entities(self, entities, entity_wrapper=None):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in _set_entities(self, entities, entity_wrapper)
217 entity_wrapper(self, ent)
218
--> 219 self._set_entity_selectables(self._entities)
220
221 def _set_entity_selectables(self, entities):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in _set_entity_selectables(self, entities)
248
249 d[entity] = (ext_info, aliased_adapter)
--> 250 ent.setup_entity(*d[entity])
251
252 def _mapper_loads_polymorphically_with(self, mapper, adapter):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/query.py in setup_entity(self, ext_info, aliased_adapter)
4169 self.selectable = ext_info.selectable
4170 self.is_aliased_class = ext_info.is_aliased_class
-> 4171 self._with_polymorphic = ext_info.with_polymorphic_mappers
4172 self._polymorphic_discriminator = ext_info.polymorphic_on
4173 self.entity_zero = ext_info
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py in __get__(self, obj, cls)
853 if obj is None:
854 return self
--> 855 obj.__dict__[self.__name__] = result = self.fget(obj)
856 return result
857
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/mapper.py in _with_polymorphic_mappers(self)
2133 def _with_polymorphic_mappers(self):
2134 if Mapper._new_mappers:
-> 2135 configure_mappers()
2136 if not self.with_polymorphic:
2137 return []
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/mapper.py in configure_mappers()
3218 has_skip = False
3219
-> 3220 Mapper.dispatch._for_class(Mapper).before_configured()
3221 # initialize properties on all mappers
3222 # note that _mapper_registry is unordered, which
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/event/attr.py in __call__(self, *args, **kw)
259
260 for fn in self.parent_listeners:
--> 261 fn(*args, **kw)
262
263 def __len__(self):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/orm/events.py in wrap(*arg, **kw)
644 arg[target_index] = arg[target_index].obj()
645 if not retval:
--> 646 fn(*arg, **kw)
647 return interfaces.EXT_CONTINUE
648 else:
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py in before_configured()
210 @event.listens_for(mapper, "before_configured")
211 def before_configured():
--> 212 self.cls.__declare_first__()
213
214 def _scan_attributes(self):
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/api.py in __declare_first__(cls)
617 @classmethod
618 def __declare_first__(cls):
--> 619 cls._sa_decl_prepare_nocascade()
620
621 @classmethod
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/api.py in _sa_decl_prepare_nocascade(cls)
624 return
625
--> 626 to_map = _DeferredMapperConfig.config_for_cls(cls)
627
628 # can't rely on 'self_and_descendants' here
~/anaconda3/lib/python3.7/site-packages/sqlalchemy/ext/declarative/base.py in config_for_cls(cls, class_)
737 @classmethod
738 def config_for_cls(cls, class_):
--> 739 return cls._configs[weakref.ref(class_)]
740
741 @classmethod
KeyError: <weakref at 0x11f0994f8; to 'DeclarativeMeta' at 0x7fde1ed53e38 (Root)>
Если я переверну порядок импорта, все в порядке ,
from db.sqlalchemy.mangadb import database as mangadb, datadb
session = mangadb.Session()
session.query(datadb.Cube).first()
<Cube (pk=7767, plateifu='7995-6102', version='v1_5_1')>
from db.sqlalchemy.archive import database as adb, sas
session = mangadb.Session()
session.query(datadb.Cube).first()
<Cube (pk=7767, plateifu='7995-6102', version='v1_5_1')>
Кто-нибудь знает, в чем причина? Почему импорт по существу несуществующего соединения с базой данных нарушает другие?