私は以前にこれに問題を抱えていましたが、それを処理する方法はセッションを維持しないことであることがわかりました。問題は、接続を長時間開いたままにしようとしていることです。__init__.py
代わりに、どこにでもインポートするユーティリティパッケージ内またはユーティリティパッケージ内で、次のようなスレッドローカルスコープセッションを使用します。
from sqlalchemy.orm import scoped_session, sessionmaker
Session = scoped_session( sessionmaker() )
次に、エンジンとメタデータを一度設定します。これにより、接続/切断するたびに構成メカニズムをスキップできます。その後、次のようにデータベースの作業を行うことができます。
session = Session()
someObject = session.query( someMappedClass ).get( someId )
# use session like normal ...
session.close()
古いオブジェクトを保持したいが、セッションを開いたままにしたくない場合は、上記のパターンを使用して、次のように古いオブジェクトを再利用できます。
session = Session()
someObject = session.merge( someObject )
# more db stuff
session.close()
The point is, you want to open your session, do your work, then close your session. This avoids timeouts very well. There are lots of options for .merge and .add that allow you to either include changes you've made to detached objects or to load new data from the db. The docs are very verbose, but once you know what you are looking for it might be a little easier to find.
To actually get all the way there and prevent the MySQL from "going away", you need to solve the issue of your connection pool keeping connections open too long and checking out an old connection for you.
To get a fresh connection, you can set the pool_recycle
option in your create_engine
call. Set this pool_recycle
to the number of seconds of time in the connection pool between checkouts that you want a new connection to be created instead of an existing connection to be returned.