简体   繁体   中英

Django - App Engine - Cloud SQL (PostgreSQL) - OperationalError: could not connect to server: Connection refused

I have Django deployed to App Engine that's connected to Cloud SQL (PostgreSQL) instance. I keep getting the following errors:

OperationalError: could not connect to server: Connection timed out 

and

OperationalError: could not connect to server: Connection refused

app.yaml

# [START django_app]
runtime: python37
service: prestige-worldwide

handlers:
# This configures Google App Engine to serve the files in the app's static
# directory.
- url: /static
  static_dir: static/
# This handler routes all requests not caught above to your main app. It is
# required when static routes are defined, but can be omitted (along with
# the entire handlers section) when there are no static files defined.
- url: /.*
  script: auto
# [END django_app]

settings.py - DATABASE configuration

ALLOWED_HOSTS = ['app-engine url','127.0.0.1']

DATABASES = {
    'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'NAME': 'postgres',
                'USER': 'postgres',
                'PASSWORD': 'admin',
                'HOST': 'instance public ip address',
                'PORT': 'ip address host',}}

It works fine locally with Cloud SQL, but doesn't work when deployed to App Engine.

Configuring DB like this solved the issue

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'admin',
    }
}
DATABASES['default']['HOST'] = '/cloudsql/instance-name'
if os.getenv('GAE_INSTANCE'):
    pass
else:
    DATABASES['default']['HOST'] = 'instance public ip address'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM