Forums

Connecting to database from outside PythonAnywhere - Lost Connection

Hi, I am learning how to do do crud operations on simple my_sql database created within my free account.

I got the sample code and modified it for personal use from PythonAnywhere.

from flask import Flask
import MySQLdb
import sshtunnel

app = Flask(__name__)

sshtunnel.SSH_TIMEOUT = 10.0
sshtunnel.TUNNEL_TIMEOUT = 10.0

with sshtunnel.SSHTunnelForwarder(
    ('ssh.pythonanywhere.com'),
    ssh_username='itookurjob', ssh_password='****',
    remote_bind_address=('itookurjob.mysql.pythonanywhere-services.com', 3306)
) as tunnel:
    connection = MySQLdb.connect(
        user='itookurjob',
        passwd='Pointer12#',
        host='127.0.0.1', port=tunnel.local_bind_port,
        db='itookurjob$mera_ghar',
    )
    # Do stuff
    @app.route('/')
    def index():
        cur = connection.cursor()
        cur.execute('''SELECT * FROM mera_ghar''')
        results = cur.fetchall()
        return str(results)

    if __name__ == '__main__':
        app.run()
    connection. Close()

However, I am getting this error:

Exception has occurred: OperationalError
(2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")
  File "/home/abdul/Documents/flask_pythonanywhere/web_app.py", line 15, in <module>
    connection = MySQLdb.connect(
                 ^^^^^^^^^^^^^^^^
MySQLdb.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0")

That would not work with free account as there is no ssh.

Just few more questions to bother if you don't mind.

  1. So I would need to upload code to run it I suppose?

  2. Don't suppose there is any way to connect from outside the website without ssh?

  1. Yes, if you want to run code, it will need to be on PythonAnywhere to run on PythonAnywhere.
  2. No