[英]Python error while connecting to cloud sql from cloud functions
我正在尝试使用Python
代码从GCP Cloud functions
连接到PostgreSQL
CloudSQL
。 我是python
的新手,所以遇到了一些错误,需要帮助来修复错误
我的代码如下:
# Don't add the "/.s.PGSQL.5432 suffix" because it will already be added back automatically by the library...
import psycopg2
import sqlalchemy
from sqlalchemy import create_engine
engine = sqlalchemy.create_engine('postgresql+psycopg2://postgres:a1b2c3d4e190@X.X.X.X/postgres_dbase')
print("connected")
function 部署良好,但 URL 失败并出现以下错误
Error: could not handle the request
它在日志中显示以下错误
Details:'Request' object has no attribute '_instantiate_plugins'
当我直接执行代码时它工作正常
$ python3 open.py
connected
我正在使用Python 3.7
更新
看起来我必须设置 DATABASE_URL 但不确定如何在 CLoud 函数中设置它。 在Cloud functions
中的Runtime environmental variable
下方添加但没有运气
DATABASE_URL="sqlite://"
不确定您是尝试从公共 IP 还是从私人连接。 但是,您可以在此处找到有关如何使用 Public IP 执行您的关注的示例。 你的代码应该看起来像
db_user = os.environ["DB_USER"]
db_pass = os.environ["DB_PASS"]
db_name = os.environ["DB_NAME"]
db_socket_dir = os.environ.get("DB_SOCKET_DIR", "/cloudsql")
cloud_sql_connection_name = os.environ["CLOUD_SQL_CONNECTION_NAME"]
pool = sqlalchemy.create_engine(
# Equivalent URL:
# postgres+pg8000://<db_user>:<db_pass>@/<db_name>
# ?unix_sock=<socket_path>/<cloud_sql_instance_name>/.s.PGSQL.5432
sqlalchemy.engine.url.URL(
drivername="postgresql+pg8000",
username=db_user, # e.g. "my-database-user"
password=db_pass, # e.g. "my-database-password"
database=db_name, # e.g. "my-database-name"
query={
"unix_sock": "{}/{}/.s.PGSQL.5432".format(
db_socket_dir, # e.g. "/cloudsql"
cloud_sql_connection_name) # i.e "<PROJECT-NAME>:<INSTANCE-REGION>:<INSTANCE-NAME>"
}
),
**db_config
)
另一方面,如果您使用的是 Private IP,您的代码中应该有类似这样的内容
db_user = os.environ["DB_USER"]
db_pass = os.environ["DB_PASS"]
db_name = os.environ["DB_NAME"]
db_host = os.environ["DB_HOST"]
# Extract host and port from db_host
host_args = db_host.split(":")
db_hostname, db_port = host_args[0], int(host_args[1])
pool = sqlalchemy.create_engine(
# Equivalent URL:
# postgres+pg8000://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name>
sqlalchemy.engine.url.URL(
drivername="postgresql+pg8000",
username=db_user, # e.g. "my-database-user"
password=db_pass, # e.g. "my-database-password"
host=db_hostname, # e.g. "127.0.0.1"
port=db_port, # e.g. 5432
database=db_name # e.g. "my-database-name"
),
**db_config
)
根据您使用的是Public IP还是Private IP ,请确保您已配置 Cloud Functions。
这适用于我将 Google App Engine 连接到来自 Google Cloud Platform 的 PostgreSQL 实例。
import psycopg2
try:
conn = psycopg2.connect(dbname='your_data_base_name', user='your_data_base_user', password='your_data_base_user_password', host='/cloudsql/project_name:region:database_instance_name')
except psycopg2.Error as e:
print("Error: Could not make connection to the Postgres database")
print(e)
cur = conn.cursor()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.