I'm working with Python, Flask, and SQLAlchemy. I've been using a local database while building my application, and it has been working fine with the following code:
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config[
'SQLALCHEMY_DATABASE_URI'] = \
'mysql+pymysql://<username>:<password>@localhost/<DBName>'
db = SQLAlchemy(app)
Now, I'm trying to get this code to connect to a remote database using the Python package sshtunnel. Here is what this code looks like:
from flask import Flask
from sshtunnel import SSHTunnelForwarder
from flask_sqlalchemy import SQLAlchemy
forwarding_server = SSHTunnelForwarder(
'1.2.3.4', #my host IP address
ssh_username="user",
ssh_password="password",
remote_bind_address=('127.0.0.1', 8080)
)
forwarding_server.start()
local_port = str(forwarding_server.local_bind_port)
app = Flask(__name__)
app.config[
'SQLALCHEMY_DATABASE_URI'] = \
'mysql+pymysql://<username>:<password>@127.0.0.1:' + local_port + '/<DBName>'
db = SQLAlchemy(app)
It SEEMS like this is connecting, but immediately after launching my flask application, I'm receiving the following error:
sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2013, 'Lost connection to MySQL server during query')
Any insight into this issue would be helpful. Thanks in advance!
You can set SQLALCHEMY_POOL_RECYCLE to a value less than SQLALCHEMY_POOL_TIMEOUT in configuration of Flask-SQLAlchemy. Check the timeouts part of the documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With