Forums

Unable to connect MySQL to Flask application

I have read and re-read past forum questions and still get the same, familiar error in connecting to MySQL from Python 3.6 running a Flask application:

Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

Here is my Flask connection method where yes, I am using ALL parameters from the Databases tab. Password even reflects what is in the my.cnf file. I even copied and pasted directly from Databases tab in case I misspelled to no avail.

import MySQLdb
...
def connection():
    dbconn = MySQLdb.connect(host = "myusername.mysql.pythonanywhere-services.com",
                             user = "myusername",
                             passwd = "******",
                             db = "myusername$mydatabasename")
    cur = dbconn.cursor()
    return (cur, dbconn)

I have tried different port (3306 and nothing); different host (mysql.server, localhost, 127.0.0.1) to no avail. PA online help pages only show Django connections.

Does the server need time to propogate changes? Is the mysql service running and can it be restarted? Please advise on issue. Thanks!

That code certainly should work fine; the error suggests that you're not setting the host parameter, but clearly you are. I see that your site is working now, and that error is no longer appearing in the logs -- were you reloading the website (using the button on the "Web" page) after making code changes?

Indeed. Reloading the website fixed the issue. All my parameters were correct and I guess the MySQL service simply needed a restart which I tried in Bash and MySQL shell but did not have su privileges. Nonetheless, reloading button from Web tab fixed it accordingly.

Thank you for your response and I hope this can help others in future. I now have successfully upsized from SQLite and even removed its large file!

Excellent, glad you got it sorted. Just for clarity, it wasn't the MySQL service that needed restarting, it was your own website's code. When you make a code change, you need to reload it from the Web page -- otherwise you'll still be running with the old code.