Unsure why I get a thread id error when using SQLAlchemy - python

I'm trying to create a database for a flask market website using models (User and Item).
When I go into my python terminal and execute the following commands:
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()
As soon as I enter db.session.commit() for the second time I get this error:
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)
I don't know why and how to fix this, does anyone know why this happens and how I can fix it?
This is the code for my models:
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}'

I was executing all those database commands in the PyCharm repl. I believe it has something to do with memory which is why it won't work in the python console on Pycharm. It works fine in a command prompt terminal and in a python file.

Related

MySQL Connection not available. Database PythonAnywhere for Telegram Bot, SQLAlchemy

The problem is this: I run the script, everything works fine. a few minutes pass and the script shuts down, leaving this error.
here is the script:
import telebot
from sqlalchemy import create_engine, Column, Integer, BigInteger
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
telegram_id = Column(BigInteger, unique=True)
money = Column(Integer)
money_for_investing = Column(Integer)
invited_friends = Column(Integer)
# Connect to the database
engine = create_engine('mysql+mysqlcon...', pool_recycle=3600)
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
# Initialize the bot and set the access token
bot = telebot.TeleBot("BOT TOKEN")
# Define the /start command handler
#bot.message_handler(commands=["start"])
def start(message):
# Get the user's input
cash = 0
user_id = message.from_user.id
investing_cash = 0
invited_friends = 0
user = session.query(User).filter(User.telegram_id == user_id).first()
# If the user is not in the database, store the data
if not user:
user = User(telegram_id=user_id, money=cash, money_for_investing=investing_cash, invited_friends=invited_friends)
session.add(user)
session.commit()
# Send a confirmation message
chat_id = message.chat.id
bot.send_message(chat_id=chat_id, text="You are registered.")
else:
# Send an error message
chat_id = message.chat.id
bot.send_message(chat_id=chat_id, text="You are already registered.")
# Start the bot
bot.polling(none_stop=True, interval=0)
Error:
20:15 ~/telegram $ python telegram_bot.py
Traceback (most recent call last):
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1719, in _execute_context
context = constructor(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/mysql/connector/connection_cext.py", line 590, in cursor
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/alexknowsbest/telegram/telegram_bot.py", line 51, in <module>
bot.polling(none_stop=True, interval=0)
File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1043, in polling
self.__threaded_polling(non_stop=non_stop, interval=interval, timeout=timeout, long_polling_timeout=long_polling_timeout,
File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1118, in __threaded_polling
raise e
File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 1074, in __threaded_polling
self.worker_pool.raise_exceptions()
File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/util.py", line 156, in raise_exceptions
raise self.exception_info
File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/util.py", line 100, in run
task(*args, **kwargs)
File "/home/alexknowsbest/.local/lib/python3.10/site-packages/telebot/__init__.py", line 6395, in _run_middlewares_and_handler
result = handler['function'](message)
File "/home/alexknowsbest/telegram/telegram_bot.py", line 34, in start
user = session.query(User).filter(User.telegram_id == user_id).first()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/query.py", line 2819, in first
return self.limit(1)._iter().first()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/query.py", line 2903, in _iter
result = self.session.execute(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/orm/session.py", line 1696, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1631, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/sql/elements.py", line 325, in _execute_on_connection
return connection._execute_clauseelement(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1498, in _execute_clauseelement
ret = self._execute_context(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1725, in _execute_context
self._handle_dbapi_exception(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 2043, in _handle_dbapi_exception
util.raise_(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/base.py", line 1719, in _execute_context
context = constructor(
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1013, in _init_compiled
self.cursor = self.create_cursor()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1361, in create_cursor
return self.create_default_cursor()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/engine/default.py", line 1364, in create_default_cursor
return self._dbapi_connection.cursor()
File "/usr/local/lib/python3.10/site-packages/sqlalchemy/pool/base.py", line 1083, in cursor
return self.dbapi_connection.cursor(*args, **kwargs)
File "/usr/local/lib/python3.10/site-packages/mysql/connector/connection_cext.py", line 590, in cursor
raise errors.OperationalError("MySQL Connection not available.")
sqlalchemy.exc.OperationalError: (mysql.connector.errors.OperationalError) MySQL Connection not available.
[SQL: SELECT users.id AS users_id, users.telegram_id AS users_telegram_id, users.money AS users_money, users.money_for_investing AS users_money_for_investing, users.invited_friends AS users_invited_friends
FROM users
WHERE users.telegram_id = %(telegram_id_1)s
LIMIT %(param_1)s]
[parameters: [{}]]
(Background on this error at: https://sqlalche.me/e/14/e3q8)
I've been trying to fix this mistake for a day, I can't. I switch to different modules and still nothing happens. please help me solve this problem. I will be very grateful to you

Flask SQLAlquemy db.commit breaks stuff

I am learning about Rest APIs and Flask. Following a simple tutorial, something doesn't work and I can't get it fixed. I create a database and I want to add something to it. My file is called "API.py" and I am using PyCharm. After running the file, I type into the Python Console in Python:
from API import db
from API import Drink
Drink.query.all() (returns an empty list, all good)
drink = Drink(name="x", description="y")
Drink.query.all() (returns an empty list, all good)
db.session.add(drink)
Drink.query.all() (returns the drink, all good)
db.session.commit()
Drink.query.all() - ERROR
I tried several things, but I can't figure it out. In the tutorial, everything is working just fine. Would you please help me fix this? Below you will find the error message and the code:
Error message:
Traceback (most recent call last):
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1800, in _execute_context
context = constructor(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1015, in _init_compiled
self.cursor = self.create_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1386, in create_cursor
return self.create_default_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1389, in create_default_cursor
return self._dbapi_connection.cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\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 5244 and this is thread id 9008.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\IPython\core\interactiveshell.py", line 3397, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-7-87e83f2944ed>", line 1, in <cell line: 1>
Drink.query.all()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\orm\query.py", line 2772, in all
return self._iter().all()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\orm\query.py", line 2907, in _iter
result = self.session.execute(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\orm\session.py", line 1712, in execute
result = conn._execute_20(statement, params or {}, execution_options)
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1705, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\sql\elements.py", line 333, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1572, in _execute_clauseelement
ret = self._execute_context(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1806, in _execute_context
self._handle_dbapi_exception(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 2124, in _handle_dbapi_exception
util.raise_(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\util\compat.py", line 208, in raise_
raise exception
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\base.py", line 1800, in _execute_context
context = constructor(
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1015, in _init_compiled
self.cursor = self.create_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1386, in create_cursor
return self.create_default_cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\lib\site-packages\sqlalchemy\engine\default.py", line 1389, in create_default_cursor
return self._dbapi_connection.cursor()
File "C:\Users\larsw\anaconda3\envs\useenv\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 5244 and this is thread id 9008.
[SQL: SELECT drink.iden AS drink_iden, drink.name AS drink_name, drink.description AS drink_description
FROM drink]
[parameters: [{}]]
(Background on this error at: https://sqlalche.me/e/14/f405)
Code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
db = SQLAlchemy(app)
class Drink(db.Model):
iden = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), unique=True, nullable=False)
description = db.Column(db.String(120))
def __repr__(self):
return f"{self.name} - {self.description}"
db.create_all()
#app.route('/')
def index():
return "Hey"
#app.route('/drinks')
def get_drinks():
return {"drinks": "drink data"}
if __name__ == "__main__":
app.run(debug=True, port=8000)
Thanks to snakecharmerb's comment, I replaced
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db"
by
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data.db?check_same_thread=False"
and it works just fine now.

Flask and sqlalchemy: Receiving a "can't adapt type 'ABCMeta'" error when posting to database

When I try to create a new user in the database I receive an error that reads
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'ABCMeta'
I've seen similar responses to this error here, but I am unsure of what this error is telling me.
Would anyone be able to give me clarity on what this error means and how can I solve it?
Code:
from extensions import db
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), nullable=False, unique=True)
email = db.Column(db.String(200), nullable=False, unique=True)
password = db.Column(db.String(200))
is_active = db.Column(db.Boolean(), default=False)
created_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now())
updated_at = db.Column(db.DateTime(), nullable=False, server_default=db.func.now(), onupdate=db.func.now())
recipes = db.relationship('Recipe', backref='user')
#classmethod
def get_user_by_username(cls, username):
return cls.query.filter_by(username=username).first()
#classmethod
def get_user_by_email(cls, email):
return cls.query.filter_by(email=email).first()
def save(self):
db.session.add(self)
db.session.commit()
Error:
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 828-615-892
127.0.0.1 - - [30/May/2022 16:15:10] "POST /users HTTP/1.1" 500 -
Traceback (most recent call last):
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1820, in _execute_context
cursor, statement, parameters, context
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
cursor.execute(statement, parameters)
psycopg2.ProgrammingError: can't adapt type 'ABCMeta'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 2328, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 2314, in wsgi_app
response = self.handle_exception(e)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 269, in error_router
return original_handler(e)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 1760, in handle_exception
reraise(exc_type, exc_value, tb)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value.with_traceback(tb)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 269, in error_router
return original_handler(e)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise
raise value.with_traceback(tb)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 1832, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/app.py", line 1818, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 458, in wrapper
resp = resource(*args, **kwargs)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask/views.py", line 88, in view
return self.dispatch_request(*args, **kwargs)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/flask_restful/__init__.py", line 573, in dispatch_request
resp = meth(*args, **kwargs)
File "/Users/lawrence/Documents/smilecook/resources/user.py", line 31, in post
user.save()
File "/Users/lawrence/Documents/smilecook/models/user.py", line 29, in save
db.session.commit()
File "<string>", line 2, in commit
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 1435, in commit
self._transaction.commit(_to_root=self.future)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 829, in commit
self._prepare_impl()
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 808, in _prepare_impl
self.session.flush()
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 3367, in flush
self._flush(objects)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 3507, in _flush
transaction.rollback(_capture_exception=True)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/util/langhelpers.py", line 72, in __exit__
with_traceback=exc_tb,
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/session.py", line 3467, in _flush
flush_context.execute()
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 456, in execute
rec.execute(self)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/unitofwork.py", line 633, in execute
uow,
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 250, in save_obj
insert,
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/orm/persistence.py", line 1241, in _emit_insert_statements
execution_options=execution_options,
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1631, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/sql/elements.py", line 326, in _execute_on_connection
self, multiparams, params, execution_options
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1508, in _execute_clauseelement
cache_hit=cache_hit,
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1863, in _execute_context
e, statement, parameters, cursor, context
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 2044, in _handle_dbapi_exception
sqlalchemy_exception, with_traceback=exc_info[2], from_=e
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/util/compat.py", line 207, in raise_
raise exception
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/base.py", line 1820, in _execute_context
cursor, statement, parameters, context
File "/Users/lawrence/Documents/smilecook/venv/lib/python3.7/site-packages/sqlalchemy/engine/default.py", line 732, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) can't adapt type 'ABCMeta'
[SQL: INSERT INTO "user" (username, email, password, is_active) VALUES (%(username)s, %(email)s, %(password)s, %(is_active)s) RETURNING "user".id]
[parameters: {'username': 'ray', 'email': 'ray#gmail.com', 'password': <class 'passlib.handlers.pbkdf2.pbkdf2_sha256'>, 'is_active': False}]
It appears the password value you are trying to save is not a string, as the typing of the password column suggests you intended, but a class -- specifically, the class passlib.handlers.pbkdf2.pbkdf2_sha256. I think maybe you meant to call that class when you were setting the value of password (i.e., do this: password = passlib.handlers.pbkdf2.pbkdf2_sha256(), with the parentheses), but you instead set it to the class you intended to call (i.e., did this: password = passlib.handlers.pbkdf2.pbkdf2_sha256, without the parentheses).
I'm not totally sure what is going on with that particular error you are getting, but it suggests that the meta class of passlib.handlers.pbkdf2.pbkdf2_sha256 is ABCMeta, which would be the case if passlib.handlers.pbkdf2.pbkdf2_sha256 is an abstract class.

Flask SQL Alchemy,showing Operational Error on Commit Sessions

The Problem is related to Flask SqlAlchemy where i am not abel to commit my Data into DataBase i have tried many ways but getting Same error ,i have uploaded all my files for that
I am making simple model by following tutorial,these are my all files
init.py
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app.config['SECRET_KEY']='123456'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////temp/test.db'
db = SQLAlchemy(app)
from BlogSite import routes
routes.py
from flask import render_template,flash,redirect, url_for
from BlogSite import app
from BlogSite.forms import RegistrationForm,SignInForm
login=False
#app.route("/home/",methods=['GET','POST'])
def home():
global login
form=SignInForm()
if form.validate_on_submit():
flash(f'Logged in successfully for ','success')
login=True
return redirect(url_for('home'))
return render_template('home.html',login=login,form=form)
#app.route("/Create_Account/",methods=['GET','POST'])
def Create_Acc():
form=RegistrationForm()
if form.validate_on_submit():
flash(f'Account Created successfully for {form.username.data}','success')
return redirect(url_for('home'))
return render_template('Create_account.html',form=form)
modals.py
from BlogSite import db
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
def __repr__(self):
return '<User %r>' % self.username
Here in repr_ method i also tried the below given code but same error is there
return f"User('{self.username}')"
run.py
from BlogSite import app
if __name__=="__main__":
app.run(debug=True)
My Tree Structure for this is as
Tree view of my File System
list of errors
and also While i was performing This At that instant Database was not Created on calling of db.create all() function and also when i just have simply named it as site.db at first at that instant Database was created but on commit error was same only
Errors i am getting as
>>> from BlogSite import db
C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\flask_sqlalchemy\__init__.py:872: FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds
significant overhead and will be disabled by default in the future. Set it to True or False to
suppress this warning.
warnings.warn(FSADeprecationWarning(
>>> db.create_all()
>>> from BlogSite.modals import User
>>> admin = User(username='admin', email='admin#example.com')
>>> db.session.add(admin)
>>> db.session.commit()
Traceback (most recent call last):
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1705, in _execute_context
self.dialect.do_execute(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\default.py", line 681, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in commit
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 1415, in commit
self._transaction.commit(_to_root=self.future)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 829, in commit
self._prepare_impl()
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 808, in _prepare_impl
self.session.flush()
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 3233, in flush
self._flush(objects)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 3373, in _flush
transaction.rollback(_capture_exception=True)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\util\langhelpers.py", line 70, in __exit__
compat.raise_(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\util\compat.py", line 198, in raise_
raise exception
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\session.py", line 3333, in _flush
flush_context.execute()
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\unitofwork.py", line 453, in execute
rec.execute(self)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\unitofwork.py", line 627, in execute
util.preloaded.orm_persistence.save_obj(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\persistence.py", line 242, in save_obj
_emit_insert_statements(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\orm\persistence.py", line 1219, in _emit_insert_statements
result = connection._execute_20(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1520, in _execute_20
return meth(self, args_10style, kwargs_10style, execution_options)
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\sql\elements.py", line 313, in _execute_on_connection
return connection._execute_clauseelement(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1389, in _execute_clauseelement
ret = self._execute_context(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1748, in _execute_context
self._handle_dbapi_exception(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1929, in _handle_dbapi_exception
util.raise_(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\util\compat.py", line 198, in raise_
raise exception
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\base.py", line 1705, in _execute_context
self.dialect.do_execute(
File "C:\Users\SPARSH PATHAK\AppData\Local\Programs\Python\Python38\lib\site-
packages\sqlalchemy\engine\default.py", line 681, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: user
[SQL: INSERT INTO user (username, email) VALUES (?, ?)]
[parameters: ('admin', 'admin#example.com')]
(Background on this error at: http://sqlalche.me/e/14/e3q8)
>>>
For Trying to solve My Problem,Thank You in Advance
Create a flask-migrate object in your application instance:
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# ...
Run your migrations:
(venv)$ flask db init
(venv)$ flask db migrate -m 'user table'
(venv)$ flask db upgrage
You should have user table after this

SQLAlchemy - Broken Pipe ERROR when trying to store large BLOB (i.e. machine learning model) to MySQL database

I would like to serialize many Gensim library Word2Vec models in MySQL database. For the purpose of my project I am utilizing: Python, Flask, SQLAlchemy, and MySQL+PyMySQL. Below you can see my Word2VecModel class which I am using in order to create word2vec table in MySQL DB:
from db.db import db
import db_models.influencer
class Word2VecModel(db.Model):
__tablename__ = "word2vec"
m_id = db.Column(db.Integer, primary_key=True)
m_username = db.Column(db.String(20), db.ForeignKey("influencer.m_username"))
m_binary = db.Column(db.LargeBinary)
influencer = db.relationship("InfluencerModel")
def __init__(self, m_binary, m_username):
self.m_binary = m_binary
self.m_username = m_username
def __repr__(self):
return '<Word2Vec {}>'.format(self.m_name)
#classmethod
def find_by_username(cls, m_username):
return cls.query.filter_by(name=m_username).first()
def save_to_db(self):
db.session.add(self)
db.session.commit()
def delete_from_db(self):
db.session.delete(self)
db.session.commit()
Whenever I try to execute:
word2vec_model = Word2VecModel(pickle.dumps(word2vec), username)
word2vec_model .save_to_db()
I get the following error message:
Traceback (most recent call last):
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 705, in _write_bytes
self._sock.sendall(data)
BrokenPipeError: [Errno 32] Broken pipe
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1278, in _execute_context
cursor, statement, parameters, context
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 593, in do_execute
cursor.execute(statement, parameters)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/cursors.py", line 163, in execute
result = self._query(query)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/cursors.py", line 321, in _query
conn.query(q)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 504, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 773, in _execute_command
self.write_packet(sql[:packet_size])
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 634, in write_packet
self._write_bytes(data)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 710, in _write_bytes
"MySQL server has gone away (%r)" % (e,))
pymysql.err.OperationalError: (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))")
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "app.py", line 117, in <module>
word2vec.save_to_db()
File "/home/stefan/PycharmProjects/NLP - Influencer Text Analysis/src/flask_api/db_models/word2vec.py", line 25, in save_to_db
db.session.commit()
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 163, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 1042, in commit
self.transaction.commit()
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 504, in commit
self._prepare_impl()
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 483, in _prepare_impl
self.session.flush()
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2523, in flush
self._flush(objects)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2664, in _flush
transaction.rollback(_capture_exception=True)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 69, in __exit__
exc_value, with_traceback=exc_tb,
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2624, in _flush
flush_context.execute()
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 422, in execute
rec.execute(self)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 589, in execute
uow,
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 245, in save_obj
insert,
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 1136, in _emit_insert_statements
statement, params
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1014, in execute
return meth(self, multiparams, params)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 298, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1133, in _execute_clauseelement
distilled_params,
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1318, in _execute_context
e, statement, parameters, cursor, context
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1512, in _handle_dbapi_exception
sqlalchemy_exception, with_traceback=exc_info[2], from_=e
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1278, in _execute_context
cursor, statement, parameters, context
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 593, in do_execute
cursor.execute(statement, parameters)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/cursors.py", line 163, in execute
result = self._query(query)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/cursors.py", line 321, in _query
conn.query(q)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 504, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 773, in _execute_command
self.write_packet(sql[:packet_size])
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 634, in write_packet
self._write_bytes(data)
File "/home/stefan/.virtualenvs/dl4cv/lib/python3.6/site-packages/pymysql/connections.py", line 710, in _write_bytes
"MySQL server has gone away (%r)" % (e,))
Killed
I've read somewhere that increasing MySQL connection timeout might help, but not in my case. Here is my DB engine configuration:
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:''#localhost/********'
app.config['PROPAGATE_EXCEPTIONS'] = True
app.config["SQLALCHEMY_ENGINE_OPTIONS"] = {"pool_recycle": 120}

Categories