Is there something I need to know before using flask-sqlalchemy in socketio handlers? (Like closing the session, if that is a thing)
Yes. The teardown_context handler that Flask-SQLAlchemy installs to get the session cleaned up at the end of each request is obviously not called in a Socket.IO event handler which has no concept of a request, so you need to clean up the session after each database usage.
This is true not only for Socket.IO, but for any situation in which you use SQLAlchemy outside of a regular Flask HTTP request handler. I like to use a custom context manager to handle the session cleanup, as described in the SQLAlchemy docs: http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it
If i close the sqlalchemy session with session.close(), does it "reopen" without making another HTTP request on the next socketio emit?
Yes, the session is reopened the next time you use it. Also, you may want to use session.remove() instead of session.close(), like flask-sqlalchemy does.
Most helpful comment
Yes. The
teardown_contexthandler that Flask-SQLAlchemy installs to get the session cleaned up at the end of each request is obviously not called in a Socket.IO event handler which has no concept of a request, so you need to clean up the session after each database usage.This is true not only for Socket.IO, but for any situation in which you use SQLAlchemy outside of a regular Flask HTTP request handler. I like to use a custom context manager to handle the session cleanup, as described in the SQLAlchemy docs: http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#when-do-i-construct-a-session-when-do-i-commit-it-and-when-do-i-close-it