django - 如何通过 Django 框架连接到 Google Cloud Postgresql?

标签 django postgresql google-cloud-platform

这是在 setting.py 文件中使用 Django 框架的本地 postgresql 连接的默认配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'LOCAL_DB_NAME',
        'USER': 'LOCAL_DB_USER',
        'PASSWORD': 'LOCAL_DB_PASS',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

如何配置它以使用 Google Cloud Postgresql 托管数据库?

最佳答案

首先你需要像这样设置数据库配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'DATABASE_NAME',
        'USER': 'DB_USER_NAME',
        'PASSWORD': 'DB_USER_PASS',
        # https://console.cloud.google.com/sql/instances
        'HOST': '<ip of your google instance>',
        'PORT': '5432', #at the moment of this writing google cloud postgresql is using the default postgresql port 5432
        'OPTIONS': {
            'sslmode': 'verify-ca', #leave this line intact
            'sslrootcert': '/your/path/to/server-ca.pem',
            "sslcert": "/your/path/to/client-cert.pem",
            "sslkey": "/your/path/to/client-key.pem",
        }
    }
}

从以下位置获取 ip/主机名:https://console.cloud.google.com/sql/instances

要创建和下载三个 pem 文件,您需要访问与此类似的内容:
https://console.cloud.google.com/sql/instances/INSTANCE_NAME/ssl
然后点击客户端证书按钮

要真正允许远程连接(如果您在本地运行 django 进行开发),那么您需要单击右侧的授权选项卡 (https://console.cloud.google.com/sql/instances/INSTANCE_NAME/authorization),然后输入您的公共(public) IP 或您组织的公共(public)网络。只有此 ip/网络将被允许访问。

要实际生成实例以及选择 postgresql,生成用户和密码,您需要遵循本教程:https://cloud.google.com/sql/docs/postgres/quickstart

现在常规 python manage.py makemigrations --settings=settings.my_settings 应该可以正常工作


如果您需要使用 psql 验证连接,那么您可以在终端中使用此命令进行连接:

psql "sslmode=verify-ca sslrootcert=/your/path/to/server-ca.pem \
sslcert=/your/path/to/client-cert.pem \
sslkey=/your/path/to/client-key.pem \
hostaddr=<ip address of google cloud instance> \
user=<your db username> dbname=<your db name>"

系统会提示您输入密码

尽情享受吧!

关于django - 如何通过 Django 框架连接到 Google Cloud Postgresql?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50132394/

相关文章:

sql - 使用 SQL 按句子中的单词位置(单词索引)排序

regex - Postgresql 正则表达式替换文本字段

java - Google App Engine 上的 Spring Boot 应用程序 : unable to find main class

google-cloud-platform - 如何从 Cloud Function 调用其他 Google API?

python - 使用未保存的相关对象保存对象

python - 您如何实现基于网络的直接存款/电子支票支付系统?

django - django 1.8 的多个数据库(mongodb[mongoengine] 和 sql )

performance - PostgreSQL 查询突然终止,因为语句超时

php - 如何从外部 PHPMyAdmin 安装连接到 Google 云 SQL 实例?

python - 带有注释的Django查询集,为什么GROUP BY应用于所有字段?