Forums

pymysql.err.OperationalError pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on 'engramar.mysql.pythonanywhere-services.com' (timed out)")

Hello guys, I am new to MySQL. Just wondering if any of you came across the same issue. It appears to be connecting to SSH but the 'conn = mysql.connect()' times out. Thanks in advance for your help.

from flask import Flask
from flaskext.mysql import MySQL
import mysql.connector
import sshtunnel

app = Flask(__name__)

sshtunnel.SSH_TIMEOUT = 5.0
sshtunnel.TUNNEL_TIMEOUT = 5.0

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='engramar', ssh_password=<password>,
    remote_bind_address=('engramar.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = mysql.connector.connect(
        user='engramar', password=<password>,
        host='127.0.0.1', port=tunnel.local_bind_port,
        database='engramar$default',
    )

print('after SSH connection')

mysql = MySQL()

# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'engramar'
app.config['MYSQL_DATABASE_PASSWORD'] = '<password>'
app.config['MYSQL_DATABASE_DB'] = 'engramar$default'
app.config['MYSQL_DATABASE_HOST'] = 'engramar.mysql.pythonanywhere-services.com'
mysql.init_app(app)

print('after app.config')

@app.route('/')
def users():
    print ('************After this statement, I will get the exception')
    conn = mysql.connect()
    cursor = conn.cursor()
    cursor.execute('''SELECT * FROM engramar$default.demo_institutionmodel;''')
    rv = cursor.fetchall()
    return str(rv)

connection.close()

if __name__ == '__main__':
    app.run(debug=True)

Regards, Engramar

When you open an SSH tunnel using a with statement, it's closed as soon as you exit the indented block that makes up that statement -- so, in the case of your code, when you reach this line:

print('after SSH connection')

...the tunnel will have been closed. If you want to run a Flask app on your local machine that can access your PythonAnywhere database, I'd suggest using the "ssh" command documented in the "Manual SSH tunnelling" section of the help page.

thanks giles. i will have a look at the link. cheers mate.

No problem -- let us know how you get on :-)