Error Thread programming error in SQLAlchemy

I have two simple tables in sqlite db.

from sqlalchemy import MetaData, Table, Column, Integer, ForeignKey, \ create_engine, String from sqlalchemy.orm import mapper, relationship, sessionmaker, scoped_session from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///dir_graph.sqlite', echo=True) session_factory = sessionmaker(bind=engine) Session = scoped_session(session_factory) session = Session() Base = declarative_base() class NodeType(Base): __tablename__ = 'nodetype' id = Column(Integer, primary_key=True) name = Column(String(20), unique=True) nodes = relationship('Node', backref='nodetype') def __init__(self, name): self.name = name def __repr__(self): return "Nodetype: %s" % self.name class Node(Base): __tablename__ = 'node' id = Column(Integer, primary_key=True) name = Column(String(20), unique=True) type_id = Column(Integer, ForeignKey('nodetype.id')) def __init__(self, _name, _type_id): self.name = _name self.type_id = _type_id Base.metadata.create_all(engine) 

After starting, I interact with the interpreter. e.g. n1 = Node ('Node1', 1) to learn about sqlalchemy. After I made session.commit () and tried another expression, for example. n2 = Node ('n2', 1) I get this error: sqlalchemy.exc.ProgrammingError: (ProgrammingError) SQLite objects created in the stream can only be used in the same stream. The object was created in thread id 3932, and this is thread id 5740 None None.

How can I continue a session after a transaction? Tnx

+2
source share
1 answer

SQLite by default prohibits the use of a single connection in multiple threads. just add the connect_args={'check_same_thread': False} parameter to the engine variable, for example

 engine = create_engine('sqlite:///dir_graph.sqlite', connect_args={'check_same_thread': False}, echo=True) 
+3
source

Source: https://habr.com/ru/post/1237140/


All Articles