Search code examples
djangogoogle-cloud-sql

Way to query CloudSql from Django app


I am trying to find an effective way to query a Google Cloud SQL database from my Django app. This app is not hosting on App Engine, just on a local server.

I have found a couple of links:

This one is a generic python connector

This answer mentions a way to do it from a local Django app, but it looks like it is more for testing.

I am not looking to use CloudSQL as my app backend, just make occasional queries to it (probably something daily to read all records in one CloudSQL table, and update a local database with the result)


Solution

  • This is possible, and not just for testing. You want something like:

    DATABASES = {
      'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'name_of_your_database',
        'USER': 'root',
        'PASSWORD': 'your_cloud_sql_root_password',
        'HOST': 'assigned_IP_of_your_cloud_sql_instance',
        'PORT': '3306',
      }
    }
    

    Where name_of_your_database was the database you created with CREATE DATABASE.

    You may also want to use SSL to protect your data as it goes over the public internet. To do this configure SSL for your instance and then add the following to the default django database options:

        'OPTIONS':  {
          'ssl': {
            'ca': '<PATH TO CA CERT>',
            'cert': '<PATH TO CLIENT CERT>',
            'key': '<PATH TO CLIENT KEY>'
          }
        }