Search code examples
pythongoogle-cloud-sqlgoogle-app-engine-pythonpymysql

Can't connect to Cloud SQL using PyMySQL


I'm trying to connect to Cloud SQL from a Python application (using PyMySQL 0.7.9) running on top of Google App Engine.

My connection string looks like this (credentials are fake of course):

pymysql.connect(unix_socket='/cloudsql/gae_project_name:cloudsql_instance_name', 
                user='user', password='', db='database_name')

The error message I receive is:

OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 97] Address family not supported by protocol)")

It's like PyMySQL doesn't recognize that I'm trying to connect through a Unix socket and tries the default value for the host argument instead (which I presume is localhost)

I am able to connect with MySQLdb with the same connection string.


Solution

  • Apparently, PyMySQL is not currently supported on the Google App Engine Standard environment, which only runs Python 2.7 (as of June 2018). This is from the maintainers of the GCP python project:

    I can confirm that pymysql is not supported in the python27 runtime. However, for most use cases, it's possible to use pymysql locally and mysqldb in production by using a try: / except ImportError: to import one or the other conditionally. As they share the same interface, you can use import as to make the two different libraries share the same name for ease of use in your code.

    See this Github thread for details