Search code examples
google-cloud-platformgoogle-app-enginegoogle-cloud-sqldjango-settingsdjango-environ

How do I connect to Google Cloud mySQL from App Engine using Django-Environ?


I am trying to connect a Django Google App engine to an instance of Cloud Mysql using django-environ. The app is unable to connect to the database, but otherwise runs successfully.

I have followed the Django tutorials for connecting to a cloudsql instance, and referenced the django-environ documentation regarding the connection string. The connection is successful from my local machine, but fails when running in the app engine environment.

My settings.py file shows:

DATABASES = {
    'default': env.db()
,}

I have tried over 20 patterns for the DATABASE_URL based on the documentation, but none have been successful. I am setting these as environment variables using google secrets manager, and I have verified that they are being pulled to the program and set as environment variables correctly.

The documentation shows mysql://user:password@host:port/dbname. I have tried this using the public IP address and port 3306. (Works on my machine). I have also tried replacing 'host:port' with the connection string and with /cloudsql/. some other combinations I have tried:

mysql://user:[email protected]:3306/dbname mysql://user:[email protected]:5432/dbname mysql://user:password@//cloudsql/<connection string/dbname

So far nothing has been successful. I have added the IAM role of SQL Client to my app engine service account.

EDIT: enocom's response was what ended up working. I had tried the same configuration many times, but I think it was something in the Cloud Console security that might have been preventing it from working. The only think that I'm sure was different is that I activated the Cloud SQL Admin API. Is that a requirement for this type of connection?


Solution

  • Have you tried something like this?

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '/cloudsql/myproject:us-central1:myinstance',
            'NAME': 'main',
            'USER': '****',
            'PASSWORD': '****',
        }
    }
    

    From Django attempts to connect to wrong socket