Connect Django to Google Cloud SQL

13,046

Solution 1

That database configuration only makes sense when connecting from AppEngine. If you want to access your CloudSQL database from your local machine using django, you should use the google.appengine.ext.django.backends.rdbms engine.

You can see the different configuration options here: https://developers.google.com/appengine/docs/python/cloud-sql/django#development-settings

EDIT: The google.appengine.ext.django.backends.rdbms engine has been deprecated. If you want to connect to Google Cloud SQL from your local machine you should use IP connectivity. You can use the Cloud SQL instance IP (IPv4 or IPv6) and connect using the standard django.db.backends.mysql engine.

Solution 2

Example connection to Google Cloud SQL in Django:

AppEngine Standard, Python 2.7:

try:
    import MySQLdb  # noqa: F401
except ImportError:
    import pymysql
    pymysql.install_as_MySQLdb()

if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine'):
    # Running on production App Engine, so connect to Google Cloud SQL using
    # the unix socket at /cloudsql/<your-cloudsql-connection string>
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '/cloudsql/<your-cloudsql-connection-string>',
            'NAME': '<your-database-name>',
            'USER': '<your-database-user>',
            'PASSWORD': '<your-database-password>',
        }
    }
else:
    # Running locally so connect to either a local MySQL instance or connect to
    # Cloud SQL via the proxy. To start the proxy via command line:
    #
    #     $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
    #
    # See https://cloud.google.com/sql/docs/mysql-connect-proxy
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '127.0.0.1', # DB's IP address
            'PORT': '3306',
            'NAME': '<your-database-name>',
            'USER': '<your-database-user>',
            'PASSWORD': '<your-database-password>',
        }
    }

Source: GCP Python Django Samples AppEngine Standard Python 2.7


AppEngine Standard, Python 3.7:

# Install PyMySQL as mysqlclient/MySQLdb to use Django's mysqlclient adapter
# See https://docs.djangoproject.com/en/2.1/ref/databases/#mysql-db-api-drivers
# for more information
import pymysql  # noqa: 402
pymysql.install_as_MySQLdb()

if os.getenv('GAE_APPLICATION', None):
    # Running on production App Engine, so connect to Google Cloud SQL using
    # the unix socket at /cloudsql/<your-cloudsql-connection string>
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '/cloudsql/[YOUR-CONNECTION-NAME]',
            'USER': '[YOUR-USERNAME]',
            'PASSWORD': '[YOUR-PASSWORD]',
            'NAME': '[YOUR-DATABASE]',
        }
    }
else:
    # Running locally so connect to either a local MySQL instance or connect to
    # Cloud SQL via the proxy. To start the proxy via command line:
    #
    #     $ cloud_sql_proxy -instances=[INSTANCE_CONNECTION_NAME]=tcp:3306
    #
    # See https://cloud.google.com/sql/docs/mysql-connect-proxy
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'HOST': '127.0.0.1', # DB's IP address
            'PORT': '3306',
            'NAME': '[YOUR-DATABASE]',
            'USER': '[YOUR-USERNAME]',
            'PASSWORD': '[YOUR-PASSWORD]',
        }
    }

Source GCP Python Django Samples AppEngine Standard Python 3.7


AppEngine Flexible:

DATABASES = {
    'default': {
        # If you are using Cloud SQL for MySQL rather than PostgreSQL, set
        # 'ENGINE': 'django.db.backends.mysql' instead of the following.
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'polls',
        'USER': '<your-database-user>',
        'PASSWORD': '<your-database-password>',
        # For MySQL, set 'PORT': '3306' instead of the following. Any Cloud
        # SQL Proxy instances running locally must also be set to tcp:3306.
        'PORT': '5432',
    }
}
# In the flexible environment, you connect to CloudSQL using a unix socket.
# Locally, you can use the CloudSQL proxy to proxy a localhost connection
# to the instance
DATABASES['default']['HOST'] = '/cloudsql/<your-cloudsql-connection-string>'
if os.getenv('GAE_INSTANCE'):
    pass
else:
    DATABASES['default']['HOST'] = '127.0.0.1' # DB's IP address

Source GCP Python Django Samples AppEngine Flexible

Share:
13,046
dbikard
Author by

dbikard

Updated on June 27, 2022

Comments

  • dbikard
    dbikard almost 2 years

    I'm trying to connect Django to the Google cloud SQL, working with python 2.7 and django 1.5 under windows. I went through the instructions on this page: https://developers.google.com/appengine/docs/python/cloud-sql/django

    My settings.py file has basic database settings of the form:

    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'INSTANCE': 'my_project:instance1',
            'NAME': 'my_database',
        }
    }
    

    With of course a proper could SQL instance and a database created through the SQL prompt of the google apis console

    When I try to run manage.py syncdb for the first time in order to obtain an OAuth2 token, I get this:

    OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)")

    Before you ask, I did make sure that both the django and google packages are in my PYTHONPATH, as well as "C:\Program Files (x86)\Google\google_appengine\lib\django-1.5"

    Any help would be really welcome!