I have built an API in Flask that performs classification on text messages with Keras. I am currently using sshtunnel
and MySQLdb
to connect to a MySQL database to fetch messages from a remote database. The entire application is wrapped in a Docker container.
I am able to establish a connection to the remote database and successfully query it, but I am opening and closing a new ssh tunnel every time a POST request comes into the API, and this slows down performance.
I have tried to open a single ssh tunnel and database connection "to rule them all", but the connection gets stale if there is no activity after an hour or so, and then API requests take forever and a day to complete.
How have you done this? Is this slowness unavoidable or is there a way to periodically refresh the ssh and database connections?
This is how I am connecting to my database for every incoming request:
with SSHTunnelForwarder(
(host, 22),
ssh_username=ssh_username,
ssh_private_key=ssh_private_key,
remote_bind_address=(localhost, 3306)
) as server:
conn = db.connect(host=localhost,
port=server.local_bind_port,
user=user,
passwd=password,
db=database)