简体   繁体   English

使用 Django 配置 Google Cloud App Engine

[英]Configuring Google Cloud App Engine w Django

I'm following this tutorial to deploy Django with Google Cloud.我正在按照本教程使用 Google Cloud 部署 Django。 At the timestamp (13:39) he goes into settings.py in the Django project in VS Code and swaps some placeholders out for his own Google Cloud credentials.在时间戳 (13:39),他在 VS Code 中进入 Django 项目中的 settings.py,并将一些占位符替换为他自己的 Google Cloud 凭据。 My settings.py however looks very different.然而,我的 settings.py 看起来非常不同。 The only thing in block caps that looks as if it might be a placeholder is "GOOGLE_CLOUD_PROJECT" and "SETTINGS_NAME".块帽中唯一看起来像是占位符的东西是“GOOGLE_CLOUD_PROJECT”和“SETTINGS_NAME”。 This is the part of the installation I can't get past because at the next step when I try to execute这是我无法通过的安装部分,因为在我尝试执行的下一步

python manage.py makemigrations

I get sent here:我被送到这里:

else:
    raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.")

Hoping someone can glance over my settings.py and identify what I'm missing why that if block is going to Exception .希望有人可以浏览一下我的 settings.py 并确定我缺少什么,为什么if块将变为Exception

One thing to note: The top imports environ and google.cloud are not resolved.需要注意的一件事:顶级导入环境google.cloud未解决。 idk if that's got anything to do with it. idk是否与它有关。 This is how the file came out the can.这就是文件从罐中出来的方式。 I don't want to mess with it in case tshtf :D我不想惹它,以防万一 tshtf :D

settings.py设置.py

import io
import os

import environ
from google.cloud import secretmanager

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# [START gaestd_py_django_secret_config]
env = environ.Env(DEBUG=(bool, False))
env_file = os.path.join(BASE_DIR, ".env")

if os.path.isfile(env_file):
    # Use a local secret file, if provided

    env.read_env(env_file)
# [START_EXCLUDE]
elif os.getenv("TRAMPOLINE_CI", None):
    # Create local settings if running with CI, for unit testing

    placeholder = (
        f"SECRET_KEY=a\n"
        f"DATABASE_URL=sqlite://{os.path.join(BASE_DIR, 'db.sqlite3')}"
    )
    env.read_env(io.StringIO(placeholder))
# [END_EXCLUDE]
elif os.environ.get("GOOGLE_CLOUD_PROJECT", None):
   # Pull secrets from Secret Manager
    project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")

    client = secretmanager.SecretManagerServiceClient()
    settings_name = os.environ.get("SETTINGS_NAME", "django_settings")
    name = f"projects/{project_id}/secrets/{settings_name}/versions/latest"
    payload = client.access_secret_version(name=name).payload.data.decode("UTF-8")

    env.read_env(io.StringIO(payload))

else:
 raise Exception("No local .env or GOOGLE_CLOUD_PROJECT detected. No secrets found.")
# [END gaestd_py_django_secret_config]

SECRET_KEY = env("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
# Change this to "False" when you are ready for production
DEBUG = True

# SECURITY WARNING: App Engine's security features ensure that it is safe to
# have ALLOWED_HOSTS = ['*'] when the app is deployed. If you deploy a Django
# app not on App Engine, make sure to set an appropriate host here.
ALLOWED_HOSTS = ["*"]

# Application definition

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

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 = "mysite.urls"

TEMPLATES = [
    {
   "BACKEND": "django.template.backends.django.DjangoTemplates",
    "DIRS": [],
    "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 = "mysite.wsgi.application"

# Database
# [START db_setup]
# [START gaestd_py_django_database_config]
# Use django-environ to parse the connection string
DATABASES = {"default": env.db()}

# If the flag as been set, configure to use proxy
if os.getenv("USE_CLOUD_SQL_AUTH_PROXY", None):
    DATABASES["default"]["HOST"] = "127.0.0.1"
    DATABASES["default"]["PORT"] = 5432

# [END gaestd_py_django_database_config]
# [END db_setup]

# Use a in-memory sqlite3 database when testing in CI systems
# TODO(glasnt) CHECK IF THIS IS REQUIRED because we're setting a val above
if os.getenv("TRAMPOLINE_CI", None):
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.sqlite3",
            "NAME": os.path.join(BASE_DIR, "db.sqlite3"),
        }
    }

# Password validation

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

# Internationalization

LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_L10N = True
USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_ROOT = "static"
STATIC_URL = "/static/"
STATICFILES_DIRS = []

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

Django wants you to provide a SECRET_KEY . Django 希望你提供一个SECRET_KEY There are a couple of ways to provide such key, but one way is to create an .env file containing the SECRET_KEY in the same folder where the manage.py file is located.有几种方法可以提供这样的密钥,但一种方法是在manage.py文件所在的同一文件夹中创建一个包含SECRET_KEY.env文件。

A SECRET_KEY can be generated using the following code snippet (run it wherever you find convenient, but don't add the resulting key string to your settings.py file):可以使用以下代码片段生成SECRET_KEY (在您认为方便的地方运行它,但不要将生成的密钥字符串添加到settings.py文件中):

from django.core.management.utils import get_random_secret_key 
get_random_secret_key()

Take the resulting output (it's a 50 character long string) and add it to the .env file with the following format:获取结果输出(它是一个 50 个字符长的字符串)并将其添加到.env文件中,格式如下:

SECRET_KEY="the-50-character-string-here"

You might potentially also have to replace BASE_DIR in the settings.py file with the following in order to properly load the .env file (note how the first row is out-commented).您可能还需要将settings.py文件中的BASE_DIR替换为以下内容,以便正确加载.env文件(注意第一行是如何注释掉的)。

#BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.getcwd()

You might run into more problems further down the road related to your database setup.在与数据库设置相关的过程中,您可能会遇到更多问题。 Check out this and this SO question.看看这个这个SO 问题。

You can also consider checking out the Guide which is what the tutorial you're referring to is following.您还可以考虑查看指南,这是您所指的教程所遵循的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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