首先你需要设置数据库配置如下:
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",
}
}
}
从https://console.cloud.google.com/sql/instances获取ip/主机名
要创建和下载三个 pem 文件,您需要访问类似于此的内容:
https://console.cloud.google.com/sql/instances/INSTANCE_NAME/ssl
然后点击客户端证书按钮
要真正允许远程连接(如果您在本地运行 django 进行开发),那么您需要单击右侧的 AUTHORIZATION 选项卡 (https://console.cloud.google.com/sql/instances/INSTANCE_NAME/authorization),然后输入您的公共 ip 或组织的公共网络。仅允许此 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>"
系统将提示您输入密码
享受吧!