不确定为什么在使用 SQLAlchemy 时出现线程 ID 错误

Unsure why I get a thread id error when using SQLAlchemy

我正在尝试使用模型(用户和项目)为烧瓶市场网站创建数据库。

当我进入 python 终端并执行以下命令时:

from market import db
from market.models import User,Item
u1 = User(username='Hay', password_hash = '123', email_address='ahus@gmail.com')
db.session.add(u1)
db.session.commit()
User.query.all()

i1 = Item(name='Iphone X', description='New iphone', barcode='123456789101', price=760)
db.session.add(i1)
db.session.commit()
i2 = Item(name='Macbook', description='New macbook', barcode='123456789102', price=1000)
db.session.add(i2)
db.session.commit()

当我第二次输入 db.session.commit() 时,我得到了这个错误:

  Traceback (most recent call last):
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1702, in _execute_context
    context = constructor(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1013, in _init_compiled
    self.cursor = self.create_cursor()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1361, in create_cursor
    return self.create_default_cursor()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1364, in create_default_cursor
    return self._dbapi_connection.cursor()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\pool\base.py", line 1083, in cursor
    return self.dbapi_connection.cursor(*args, **kwargs)
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
The above exception was the direct cause of the following exception:


Traceback (most recent call last):
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3448, in _flush
    flush_context.execute()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 456, in execute
    rec.execute(self)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 630, in execute
    util.preloaded.orm_persistence.save_obj(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 244, in save_obj
    _emit_insert_statements(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\persistence.py", line 1221, in _emit_insert_statements
    result = connection._execute_20(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1614, in _execute_20
    return meth(self, args_10style, kwargs_10style, execution_options)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\sql\elements.py", line 325, in _execute_on_connection
    return connection._execute_clauseelement(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1481, in _execute_clauseelement
    ret = self._execute_context(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1708, in _execute_context
    self._handle_dbapi_exception(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2026, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1702, in _execute_context
    context = constructor(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1013, in _init_compiled
    self.cursor = self.create_cursor()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1361, in create_cursor
    return self.create_default_cursor()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 1364, in create_default_cursor
    return self._dbapi_connection.cursor()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\pool\base.py", line 1083, in cursor
    return self.dbapi_connection.cursor(*args, **kwargs)
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
[SQL: INSERT INTO item (name, price, barcode, description, owner) VALUES (?, ?, ?, ?, ?)]
[parameters: [{'barcode': '123456789102', 'price': 760, 'description': 'New laptop', 'name': 'Laptop', 'owner': None}]]
(Background on this error at: https://sqlalche.me/e/14/f405)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 966, in _rollback_impl
    self.engine.dialect.do_rollback(self.connection)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 682, in do_rollback
    dbapi_connection.rollback()
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<string>", line 2, in commit
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 1431, in commit
    self._transaction.commit(_to_root=self.future)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 829, in commit
    self._prepare_impl()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
    self.session.flush()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3348, in flush
    self._flush(objects)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3488, in _flush
    transaction.rollback(_capture_exception=True)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\langhelpers.py", line 84, in __exit__
    compat.raise_(value, with_traceback=traceback)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 3488, in _flush
    transaction.rollback(_capture_exception=True)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 900, in rollback
    util.raise_(rollback_err[1], with_traceback=rollback_err[2])
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\orm\session.py", line 865, in rollback
    t[1].rollback()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2340, in rollback
    self._do_rollback()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2544, in _do_rollback
    self._close_impl(try_deactivate=True)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2527, in _close_impl
    self._connection_rollback_impl()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2519, in _connection_rollback_impl
    self.connection._rollback_impl()
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 968, in _rollback_impl
    self._handle_dbapi_exception(e, None, None, None, None)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2026, in _handle_dbapi_exception
    util.raise_(
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\util\compat.py", line 207, in raise_
    raise exception
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\base.py", line 966, in _rollback_impl
    self.engine.dialect.do_rollback(self.connection)
  File "C:\Users\simer\PycharmProjects\MarketWebsite_Flask\venv\lib\site-packages\sqlalchemy\engine\default.py", line 682, in do_rollback
    dbapi_connection.rollback()
sqlalchemy.exc.ProgrammingError: (sqlite3.ProgrammingError) SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 24304 and this is thread id 12744.
(Background on this error at: https://sqlalche.me/e/14/f405)

我不知道为什么以及如何解决这个问题,有谁知道为什么会发生这种情况以及我该如何解决?

这是我的模型的代码:

from market import db

class User(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(length=30), nullable=False, unique=True)
    email_address = db.Column(db.String(length=50), nullable=False, unique=True)
    password_hash = db.Column(db.String(length=60), nullable=False)
    budget = db.Column(db.Integer(), nullable=False, default=1000) # Users have 1000 points to spend at the start
    items = db.relationship('Item', backref='owned_user', lazy=True)

class Item(db.Model):
    id = db.Column(db.Integer(), primary_key=True)

    name = db.Column(db.String(length=30), nullable=False, unique=True)

    price = db.Column(db.Integer(), nullable=False)

    barcode = db.Column(db.String(length=12), nullable=False, unique=True)

    description = db.Column(db.String(length=1000), nullable=False)

    owner = db.Column(db.Integer(), db.ForeignKey('user.id'))
    def __repr__(self):
        return f'Item {self.name}'

我在 PyCharm repl 中执行了所有这些数据库命令。我相信它与内存有关,这就是为什么它不能在 Pycharm 上的 python 控制台中工作的原因。它在命令提示符终端和 python 文件中工作正常。