这是在 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/