SQLAlchemy 中的 ProgrammingError 线程错误 [英] ProgrammingError Thread error in SQLAlchemy

查看:35
本文介绍了SQLAlchemy 中的 ProgrammingError 线程错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个 sqlite 数据库中有两个简单的表.

I have a two simple tables in a 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) 

运行后我与解释器交互.例如n1= Node('Node1',1) 了解 sqlalchemy.在我做了 session.commit() 并尝试另一个语句之后,例如n2 = Node('n2',1) 我收到这个错误:sqlalchemy.exc.ProgrammingError: (ProgrammingError) 在一个线程中创建的 SQLite 对象只能在同一个线程中使用.该对象是在线程 ID 3932 中创建的,这是线程 ID 5740 无无.

After the run I interact with the interpreter. e.g. n1= Node('Node1',1) to learn about sqlalchemy. After I did a session.commit() and try another statement e.g. n2 = Node('n2',1) I get this error: sqlalchemy.exc.ProgrammingError: (ProgrammingError) SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 3932 and this is thread id 5740 None None.

提交后如何继续会话?tnx

How can I continue a session after I did a commit ? tnx

推荐答案

SQLite 默认禁止在多个线程中使用单个连接.只需将 connect_args={'check_same_thread': False} 参数添加到您的 engine 变量中,例如

SQLite by default prohibits the usage of a single connection in more than one thread. just add connect_args={'check_same_thread': False} parameter to your engine variable like

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

根据sqlite3.connect:

默认情况下,check_same_threadTrue 并且只有创建线程可以使用连接.如果设置False,返回的连接可能是多线程共享.当使用多线程时相同的连接写入操作应由用户序列化为避免数据损坏.

By default, check_same_thread is True and only the creating thread may use the connection. If set False, the returned connection may be shared across multiple threads. When using multiple threads with the same connection writing operations should be serialized by the user to avoid data corruption.

这篇关于SQLAlchemy 中的 ProgrammingError 线程错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆