Can’t connect to MySQL server on ‘localhost’ (Google SQL)

I assume, you came across this article while struggling to connect to google cloud SQL with sqlalchemy. The google documentation is not the best one, because there is so many versions of google libraries. Some of them even deprecated and the examples often doesn’t reflect these changes. Moreover examples for local environment are often different from that one used in production and that was case. In the documentation there is snippet:

db = sqlalchemy.create_engine(
    sqlalchemy.engine.url.URL(
        drivername='mysql+pymysql',
        username=db_user,
        password=db_pass,
        database=db_name,
        query={
            'unix_socket': '/cloudsql/{}'.format(cloud_sql_connection_name)
        }
    ),

)

But with this snippet you get remarkable OperationalError:

sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 2] No such file or directory)")

After few hours of googling and dubugging I have tried to comment out the query attribute and voilà. So when using the cloud_sql_proxy you have to omit the query attribute:

db = sqlalchemy.create_engine(
    sqlalchemy.engine.url.URL(
        drivername='mysql+pymysql',
        username=db_user,
        password=db_pass,
        database=db_name,
    ),
)

Heureka! It work. But wait. What happens when you upload it to Google Cloud? 🤔 Yes it breaks down. So you have to add the query lines when uploading it to google app engine.

Buy me a coffeeOut of coffee 😱, please help!