Я пишу скрипт, который импортирует некоторые данные из файла CSV в базу данных Postgres. Сценарий выглядит следующим образом:
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = <my-db-uri>
app.config['WHOOSH_INDEX_PATH'] = <my-whoosh-directory-path>
db = flask_sqlalchemy.SQLAlchemy(app)
class MyClass(db.Model):
__tablename__ = 'my_table'
__searchable__ = ['first_param']
first_param = db.Column(db.Unicode)
second_param = db.Column(db.Unicode)
third_param = db.Column(db.Unicode)
def load_data(filepath, session):
try:
with open(filepath, 'r', encoding=encoding) as file:
datareader = csv.reader(file, delimiter=';')
headers = next(datareader)
for row in datareader:
entry = {row[i] for i, c in enumerate(headers)}
session.add(MyClass(**entry))
session.commit()
return True
except Exception as e:
session.rollback()
return False
finally:
session.remove()
if __name__ == '__main__':
db.create_all()
data_loaded = load_data(filepath = <my-file-path>, session = db.session)
Некоторые из ненужных деталей удалены из приведенного выше сценария. Сценарии работают нормально, если я удаляю строку __searchable__
из MyClass
. Однако, когда я добавляю эту строку, появляется следующая ошибка:
This session is in 'committed' state; no further SQL can be emitted within this transaction.
Traceback (most recent call last):
File "data_importer.py", line 169, in load_data
session.commit()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 906, in commit
self.transaction.commit()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 468, in commit
self.session.dispatch.after_commit(self.session)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
fn(*args, **kw)
File "/usr/local/lib/python3.7/site-packages/flask_sqlalchemy/__init__.py", line 219, in after_commit
models_committed.send(session.app, changes=list(d.values()))
File "/usr/local/lib/python3.7/site-packages/blinker/base.py", line 267, in send
for receiver in self.receivers_for(sender)]
File "/usr/local/lib/python3.7/site-packages/blinker/base.py", line 267, in <listcomp>
for receiver in self.receivers_for(sender)]
File "/usr/local/lib/python3.7/site-packages/flask_whooshalchemy/__init__.py", line 153, in _post_flush
attrs[k] = str(getattr(v, k))
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/attributes.py", line 237, in __get__
return self.impl.get(instance_state(instance), dict_)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/attributes.py", line 579, in get
value = state._load_expired(state, passive)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/state.py", line 592, in _load_expired
self.manager.deferred_scalar_loader(self, toload)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/loading.py", line 698, in load_scalar_attributes
only_load_props=attribute_names)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/loading.py", line 223, in load_on_ident
return q.one()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 2814, in one
ret = self.one_or_none()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 2784, in one_or_none
ret = list(self)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 2855, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 2876, in _execute_and_instances
close_with_result=True)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 2885, in _get_bind_args
**kw
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/query.py", line 2867, in _connection_from_session
conn = self.session.connection(**kw)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 998, in connection
execution_options=execution_options)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1003, in _connection_for_bind
engine, execution_options)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 382, in _connection_for_bind
self._assert_active()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 258, in _assert_active
"This session is in 'committed' state; no further "
sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "data_importer_2.py", line 459, in <module>
ldap_data_loaded = load_data(filepath = args.data_dir, session = db.session, added_on=last_update)
File "data_importer_2.py", line 180, in load_data
session.rollback()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 870, in rollback
self.transaction.rollback()
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 477, in rollback
self._assert_active(prepared_ok=True, rollback_ok=True)
File "/usr/local/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 258, in _assert_active
"This session is in 'committed' state; no further "
sqlalchemy.exc.InvalidRequestError: This session is in 'committed' state; no further SQL can be emitted within this transaction.
Кто-нибудь знает, где может быть проблема? Я искал решение, но не смог найти ни одного!