import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
engine = create_engine("postgres://kali:kali#localhost/mydb")
db = scoped_session(sessionmaker(bind=engine))
def main():
flights = db.execute ("SELECT origin, destination, duration FROM flights;").fetchall()
for flight in flights:
print(f"{flight.origin} to {flight.destination}, {flight.duration} minutes.")
if __name__ == "__main__":
main()
After i execute python , he send for me:
I do not know the reason
Error:
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.UndefinedTable: relation "flights" does not exist
LINE 1: SELECT origin, destination, duration FROM flights
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "list.py", line 18, in <module>
main()
File "list.py", line 13, in main
flights = db.execute("SELECT origin, destination, duration FROM flights").fetchall()
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/orm/scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/orm/session.py", line 1278, in execute
clause, params or {}
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 984, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/sql/elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1103, in _execute_clauseelement
distilled_params,
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1288, in _execute_context
e, statement, parameters, cursor, context
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1482, in _handle_dbapi_exception
sqlalchemy_exception, with_traceback=exc_info[2], from_=e
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "flights" does not exist
LINE 1: SELECT origin, destination, duration FROM flights
^
[SQL: SELECT origin, destination, duration FROM flights]
(Background on this error at: http://sqlalche.me/e/f405)
root#ubuntu:~/lecture3# python3 list2.py
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
psycopg2.errors.UndefinedTable: relation "flights" does not exist
LINE 1: SELECT origin, destination, duration FROM flights;
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "list2.py", line 15, in <module>
main()
File "list2.py", line 10, in main
flights = db.execute ("SELECT origin, destination, duration FROM flights;").fetchall()
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/orm/scoping.py", line 162, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/orm/session.py", line 1278, in execute
clause, params or {}
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 984, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/sql/elements.py", line 293, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1103, in _execute_clauseelement
distilled_params,
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1288, in _execute_context
e, statement, parameters, cursor, context
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1482, in _handle_dbapi_exception
sqlalchemy_exception, with_traceback=exc_info[2], from_=e
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/util/compat.py", line 178, in raise_
raise exception
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py", line 1248, in _execute_context
cursor, statement, parameters, context
File "/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/default.py", line 588, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "flights" does not exist
LINE 1: SELECT origin, destination, duration FROM flights;
^
[SQL: SELECT origin, destination, duration FROM flights;]
(Background on this error at: http://sqlalche.me/e/f405)
I try change "engine = create_engine("postgres://kali:kali#localhost/mydb")" to "engine = create_engine(os.getenv("postgres://kali:kali#localhost:5432/mydb"))" and:
" AttributeError: 'NoneType' object has no attribute '_instantiate_plugins' "
sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedTable) relation "flights" does not exist
Means that you don't have a table by the name of(flights) in your database.
Create the table like this:
CREATE TABLE flights(id SERIAL PRIMARY KEY NOT NULL, origin VARCHAR NOT NULL, destination VARCHAR NOT NULL, duration INTEGER NOT NULL);
Then try running your application, it should work.
Related
I am trying to write to an in-memory SQLite database in multiple threads. According to SQLAlchemy docs this is possible. However, in practice I cannot reliably get it to work. I have tried with both scoped_session and without, yielding the same results. Strangely enough, if I pass echo=True to create_engine the code works every time, maybe because it forces the engine to synchronously print all statements to the screen. Code sample and exceptions are below.
EDIT: The more I look into this, the more I realize that SQLite is just not very good at concurrency for write operations. The section on High Concurrency says that while an unlimited amount of readers are allowed, there can only be one writer at any given time. A better approach here would be to queue all write operations instead of trying to achieve any level of concurrency. However I am still open to suggestions if anyone has managed to find a solution.
import threading
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.pool import StaticPool
from sqlalchemy.orm import sessionmaker, scoped_session
in_memory_engine = create_engine('sqlite://', connect_args={'check_same_thread':False}, poolclass=StaticPool)
Base = declarative_base()
class Item(Base):
__tablename__ = 'items'
id = Column(Integer, primary_key=True, autoincrement=True)
data = Column(Integer)
Base.metadata.create_all(bind=in_memory_engine)
session_factory = sessionmaker(bind=in_memory_engine)
Session = scoped_session(session_factory)
def insert_items():
session = Session()
for i in range(1000):
session.add(Item(data=i))
session.commit()
Session.remove()
for i in range(10):
t = threading.Thread(target=insert_items)
t.start()
Exception in thread Thread-6:
Traceback (most recent call last):
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "c:\python\lib\site-packages\sqlalchemy\engine\default.py", line 552, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: cannot start a transaction within a transaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "c:\python\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "c:\python\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "<ipython-input-1-e1040f59c94e>", line 26, in insert_items
session.commit()
File "c:\python\lib\site-packages\sqlalchemy\orm\session.py", line 1027, in commit
self.transaction.commit()
File "c:\python\lib\site-packages\sqlalchemy\orm\session.py", line 494, in commit
self._prepare_impl()
File "c:\python\lib\site-packages\sqlalchemy\orm\session.py", line 473, in _prepare_impl
self.session.flush()
File "c:\python\lib\site-packages\sqlalchemy\orm\session.py", line 2459, in flush
self._flush(objects)
File "c:\python\lib\site-packages\sqlalchemy\orm\session.py", line 2597, in _flush
transaction.rollback(_capture_exception=True)
File "c:\python\lib\site-packages\sqlalchemy\util\langhelpers.py", line 68, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "c:\python\lib\site-packages\sqlalchemy\util\compat.py", line 153, in reraise
raise value
File "c:\python\lib\site-packages\sqlalchemy\orm\session.py", line 2557, in _flush
flush_context.execute()
File "c:\python\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 422, in execute
rec.execute(self)
File "c:\python\lib\site-packages\sqlalchemy\orm\unitofwork.py", line 589, in execute
uow,
File "c:\python\lib\site-packages\sqlalchemy\orm\persistence.py", line 245, in save_obj
insert,
File "c:\python\lib\site-packages\sqlalchemy\orm\persistence.py", line 1138, in _emit_insert_statements
statement, params
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 988, in execute
return meth(self, multiparams, params)
File "c:\python\lib\site-packages\sqlalchemy\sql\elements.py", line 287, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 1107, in _execute_clauseelement
distilled_params,
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 1253, in _execute_context
e, statement, parameters, cursor, context
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 1473, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "c:\python\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "c:\python\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "c:\python\lib\site-packages\sqlalchemy\engine\default.py", line 552, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) cannot start a transaction within a transaction
[SQL: INSERT INTO items (data) VALUES (?)]
[parameters: (780,)]
(Background on this error at: http://sqlalche.me/e/e3q8)
Exception in thread Thread-7:
Traceback (most recent call last):
File "c:\python\lib\site-packages\sqlalchemy\engine\base.py", line 1249, in _execute_context
cursor, statement, parameters, context
File "c:\python\lib\site-packages\sqlalchemy\engine\default.py", line 552, in do_execute
cursor.execute(statement, parameters)
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.
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}
I am writing on a Dash app and using SQL alchemy for the database. I want to make the creation of the database automated so I have a few lines of code to create the database if it does not exist.
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Float
from sqlalchemy_utils import create_database, database_exists
engine = create_engine(SQLALCHEMY_DATABASE_URI, echo = True)
create_database(SQLALCHEMY_DATABASE_URI)
meta = MetaData()
flagged_vendors_table = Table(
'flagged_vendors', meta,
Column(vendor_col, String, primary_key = True),
Column(flag_col, Integer)
)
meta.create_all(engine)
This seems to work well as per the echo:
2020-01-21 09:28:30,604 INFO sqlalchemy.engine.base.Engine
CREATE TABLE flagged_vendors (
"Vendor PRS_description" VARCHAR NOT NULL,
"Flag" INTEGER,
PRIMARY KEY ("Vendor PRS_description")
)
2020-01-21 09:28:30,608 INFO sqlalchemy.engine.base.Engine ()
2020-01-21 09:28:30,639 INFO sqlalchemy.engine.base.Engine COMMIT
However when I execute the app I get the following error:
Traceback (most recent call last):
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
cursor.execute(statement, parameters)
sqlite3.OperationalError: no such table: flagged_vendors
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\pandas\io\sql.py", line 518, in to_sql
method=method,
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\pandas\io\sql.py", line 1319, in to_sql
table.create()
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\pandas\io\sql.py", line 647, in create
self.pd_sql.drop_table(self.name, self.schema)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\pandas\io\sql.py", line 1367, in drop_table
self.get_table(table_name, schema).drop()
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\sql\schema.py", line 884, in drop
bind._run_visitor(ddl.SchemaDropper, self, checkfirst=checkfirst)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 2049, in _run_visitor
conn._run_visitor(visitorcallable, element, **kwargs)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1618, in _run_visitor
visitorcallable(self.dialect, self, **kwargs).traverse_single(element)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\sql\visitors.py", line 138, in traverse_single
return meth(obj, **kw)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 1002, in visit_table
self.connection.execute(DropTable(table))
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 982, in execute
return meth(self, multiparams, params)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\sql\ddl.py", line 72, in _execute_on_connection
return connection._execute_ddl(self, multiparams, params)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1044, in _execute_ddl
compiled,
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1250, in _execute_context
e, statement, parameters, cursor, context
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1476, in _handle_dbapi_exception
util.raise_from_cause(sqlalchemy_exception, exc_info)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\util\compat.py", line 398, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\util\compat.py", line 152, in reraise
raise value.with_traceback(tb)
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\base.py", line 1246, in _execute_context
cursor, statement, parameters, context
File "C:\Users\LIAG8802\Documents\Procurement_analytics\venv\lib\site-packages\sqlalchemy\engine\default.py", line 581, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: flagged_vendors
[SQL:
DROP TABLE flagged_vendors]
(Background on this error at: http://sqlalche.me/e/e3q8)
The traceback is not leading to any line in my code, which is an issue that I am trying to investigate here, but I believe there is only one part in my code that could cause the error:
def to_storage(df, storage_info):
storage_type = storage_info["storage_type"]
if storage_type == "sql":
db_uri = storage_info["db_uri"]
engine = create_engine(db_uri, echo = False, pool_pre_ping=True)
table_name = storage_info["table_name"]
df.to_sql(table_name, engine, if_exists = "replace")
It is very strange because the code is supposed to drop the table only if it exists. One last element: this issue seems to appear only if there is no existing database at the specified URI when I launch the app.
The issue I am having is with the mixing of sqlalchemy sessions with flask-sqlalchemy session. So for context, I am running a flask-restful app on the background and I have a file (runnable.py) with a main method which is supposed to run periodically for an average period of 4 weeks.
This file uses its own session (pure sqlalchemy session) and connects to this app (which uses flask-sqlalchemy session).
After a few hours (sometimes 1 day), I get this error
Traceback (most recent call last):
File "/home/ubuntu/cron/runnable.py", line 781, in <module>
main()
File "/home/ubuntu/cron/runnable.py", line 677, in main
db_process_attendee(attendee, eid, event_id)
File "/home/ubuntu/cron/runnable.py", line 78, in db_process_attendee
update_attendee_information(attendee, attributes, eid, event_id)
File "/home/ubuntu/cron/runnable.py", line 117, in update_attendee_information
update_attendee_profile(attendee, id_attendee_login, eid, event_id)
File "/home/ubuntu/cron/runnable.py", line 291, in update_attendee_profile
generate_company_tags_lower.generate_company_tags(id_attendee_login)
File "/home/ubuntu/cron/app/util/generate_company_tags_lower.py", line 28, in generate_company_tags
filter(a_p.id_attendee_login == id_attendee_login).\
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2426, in scalar
ret = self.one()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2395, in one
ret = list(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2438, in __iter__
return self._execute_and_instances(context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 2453, in _execute_and_instances
result = conn.execute(querycontext.statement, self._params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 729, in execute
return meth(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/elements.py", line 322, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 826, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 958, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1159, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 199, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 951, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 436, in do_execute
cursor.execute(statement, parameters)
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 134, in execute
result = self._query(query)
File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 282, in _query
conn.query(q)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 767, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 957, in _execute_command
self._write_bytes(prelude + sql[:chunk_size-1])
File "/usr/local/lib/python2.7/dist-packages/pymysql/connections.py", line 916, in _write_bytes
raise err.OperationalError(2006, "MySQL server has gone away (%r)" % (e,))
sqlalchemy.exc.OperationalError: (OperationalError) (2006, "MySQL server has gone away (error(110, 'Connection timed out'))") 'SELECT a_p.id_attendee_profile AS a_p_id_attendee_profile, a_p.id_attendee_login AS a_p_id_attendee_login \nFROM a_p \nWHERE a_p.id_attendee_login = %s' (128368,)
I tried the following suggestions but they did not work:
• In my app config, adding "pymysql" to the SQLALCHEMY_DATABASE_URI
• Doing a db.session.commit() when I enter generate_company_tags(id_attendee_login) before writing a sql select query. I thought it would flush the session.
Btw, the sqlalchemy pool recycle value is set to less than the max in AWS RDS.
Any suggestions on how I can go solving this?
When i run the dbManager.create_all() command, it runs with out errors but fails to create the tables. When i delete the database and run the create_all() command, i get the no such database as ##### error which i should get but when the database does exist, nothing happens.
Please can anyone see what i'm doing wrong?
from blogconfig import dbManager
class Art(dbManager.Model):
id = dbManager.Column(dbManager.Integer, primary_key = True)
title = dbManager.Column(dbManager.String(64), index = True, unique = True)
content = dbManager.Column(dbManager.Text(5000))
def __repr__(self):
return '<Art %r>' %(self.title)
EDIT
This is the shell command
from blogconfig import dbManager
>>> dbManager.create_all()
import models
>>> a = models.Art(title='des', content='asdfvhbdjbjdn')
>>> dbManager.session.add(a)
>>> dbManager.session.commit()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/scoping.py", line 149, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 721, in commit
self.transaction.commit()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 354, in commit
self._prepare_impl()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 334, in _prepare_impl
self.session.flush()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1818, in flush
self._flush(objects)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1936, in _flush
transaction.rollback(_capture_exception=True)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/langhelpers.py", line 58, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/session.py", line 1900, in _flush
flush_context.execute()
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 372, in execute
rec.execute(self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 525, in execute
uow
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 64, in save_obj
table, insert)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/persistence.py", line 569, in _emit_insert_statements
execute(statement, params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 662, in execute
params)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 761, in _execute_clauseelement
compiled_sql, distilled_params
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 874, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 1024, in _handle_dbapi_exception
exc_info
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/util/compat.py", line 195, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/base.py", line 867, in _execute_context
context)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/engine/default.py", line 324, in do_execute
cursor.execute(statement, parameters)
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 174, in execute
self.errorhandler(self, exc, value)
File "/usr/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
raise errorclass, errorvalue
sqlalchemy.exc.ProgrammingError: (ProgrammingError) (1146, "Table 'blog.art' doesn't exist") 'INSERT INTO art (title, content) VALUES (%s, %s)' ('des', 'asdfvhbdjbjdn')
dbManager will not know about the models you define in other modules unless they are imported before running create_all.
In a real application this shouldn't matter because running the flask app should set up the db and import views/blueprints to register them. Since the views use the models, the models are indirectly imported and are available to the dbManager.
Either import your models in the blogconfig module after creating the dbManager instance, or change the order of you shell commands to be
>>> from blogconfig import dbManager
>>> import models
>>> dbManager.create_all()
SQLAlchemy will only create tables, the database must already exist, which is why you're seeing the other error when you delete the database.