Home > Software design >  Django deploy on App Engine raise error: connection to server at "127.0.0.1", port 5432 fa
Django deploy on App Engine raise error: connection to server at "127.0.0.1", port 5432 fa

Time:08-28

i am trying to deploy my django web app on Google Cloud App Engine, but are running to a connection error. This is after I have done all the configuration like main.py, entry point, app.yaml.

After doing some digging, they all point to my postgresql database blocking my connections somehow, but i checked and my database is up and running on sql cloud.

Here is the screenshot of the error:

[the error image][1]: https://i.stack.imgur.com/bDIfY.png

Here is my app.yaml file:

# [START django_app]
runtime: python38

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: django_blog.wsgi.application

env_variables:
    APPENGINE_URL: https://engineblog.wn.r.appspot.com

#entrypoint: gunicorn -b :$PORT django_project.wsgi:main

inbound_services:
- warmup

# Only pure Python libraries can be vendored
# Python libraries that use C extensions can
# only be included if they are part of the App Engine SDK 
# Using Third Party Libraries: https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27
# libraries:
# - name: MySQLdb
#   version: 1.2.5
# [END django_app].

Here is my home.html which is the file that django show for the error

{% extends "base.html" %}

{% block content %}
{% for post in post_list %}
<div >
    <h2>
        <a href="">{{ post.title }}</a>
        <p>{{ post.body }}</p>
    </h2>
</div>
{% endfor %}
{% endblock content %}

and my setting.py file:

"""
Django settings for django_project project.

Generated by 'django-admin startproject' using Django 4.0.6.

For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent

# Build paths inside the project like this: BASE_DIR / 'subdir'.


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "this is secret"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["*", "https://engineblog.wn.r.appspot.com"]


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "blog.apps.BlogConfig",
]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "django_project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [BASE_DIR / "templates"],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
            ],
        },
    },
]

WSGI_APPLICATION = "django_project.wsgi.application"

EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"


# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases

if os.getenv("TRAMPOLINE_CI", None):
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
        }
    }
WSGI_APPLICATION = "django_project.wsgi.application"

import pymysql

pymysql.install_as_MySQLdb()

# [START db_setup]
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.postgresql_psycopg2",
            "HOST": "/cloudsql/connectionstring",
            "NAME": "dbname",
            "USER": "dbuser",
            "PASSWORD": "dbpassword",
        }
    }

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.postgresql_psycopg2",
            "HOST": "127.0.0.1",
            "PORT": "5432",
            "NAME": "dbname",
            "USER": "dbuser",
            "PASSWORD": "db_password",
        }
    }

# [END db_setup]
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_ROOT = "static"

STATIC_URL = "/static/"
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

I am at my witt end here, so I would appreciate the help [1]: https://i.stack.imgur.com/bDIfY.png

CodePudding user response:

According to this documentation, to check if you're running in Production or not, you should be doing

if os.getenv('GAE_ENV', '').startswith('standard'):
  # Production in the standard environment
else:
  # Local execution.

If you print the dict for os.getenv, you will see a value of gunicorn/20.1.0. for "SERVER_SOFTWARE"

  • Related