【问题标题】:Python error while connecting to cloud sql from cloud functions从云函数连接到云 sql 时出现 Python 错误
【发布时间】:2021-04-24 19:15:56
【问题描述】:

我正在尝试使用 Python 代码从 GCP Cloud functions 连接到 PostgreSQLCloudSQL 实例。我是 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")

该功能已正常部署,但 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 functionsRuntime environmental variable 下方添加但没有运气

 DATABASE_URL="sqlite://"

https://github.com/sqlalchemy/sqlalchemy/issues/5330

【问题讨论】:

    标签: python-3.x postgresql google-cloud-functions psycopg2 google-cloud-sql


    【解决方案1】:

    不确定您是尝试从公共 IP 还是从私有 IP 连接。但是,here 您可以找到有关如何使用公共 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
    )
    

    另一方面,如果您使用的是私有 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 来配置您的云功能。

    【讨论】:

      【解决方案2】:

      这适用于我将 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-12
        • 1970-01-01
        • 2014-12-08
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        • 2020-11-28
        相关资源
        最近更新 更多