簡體   English   中英

Django 在 App Engine 上部署引發錯誤:連接到“127.0.0.1”的服務器,端口 5432 失敗:

[英]Django deploy on App Engine raise error: connection to server at "127.0.0.1", port 5432 failed:

我正在嘗試在 Google Cloud App Engine 上部署我的 django Web 應用程序,但運行時出現連接錯誤。 這是在我完成所有配置(如 main.py、入口點、app.yaml)之后。

在進行了一些挖掘之后,它們都指向我的 postgresql 數據庫以某種方式阻止了我的連接,但我檢查了一下,我的數據庫已啟動並在 sql cloud 上運行。

這是錯誤的屏幕截圖:

[錯誤圖片][1]:https://i.stack.imgur.com/bDIfY.png

這是我的app.yaml文件:

# [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].

這是我的home.html ,這是 django 顯示的錯誤文件

{% extends "base.html" %}

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

和我的setting.py文件:

"""
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"

我在這里,所以我很感激幫助 [1]: https ://i.stack.imgur.com/bDIfY.png

根據此文檔,要檢查您是否在生產中運行,您應該這樣做

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

如果您打印 os.getenv 的 dict,您將看到gunicorn/20.1.0. 對於“SERVER_SOFTWARE”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM