简体   繁体   English

使用 Python 的 SQLALCHEMY 无法连接到云 SQL (PostgreSQL)

[英]Having Trouble Connecting to Cloud SQL (PostgreSQL) using Python's SQLALCHEMY

I set up the Cloud SQL instance on Google Cloud Platform and followed the official instructions, but don't seem to be able to connect to the Cloud SQL instance.我在 Google Cloud Platform 上设置了 Cloud SQL 实例并按照官方说明进行操作,但似乎无法连接到 Cloud SQL 实例。 When I try to do a sanity check and access the PostgreSQL db through Cloud Shell, I'm able to connect successfully though.当我尝试进行完整性检查并通过 Cloud Shell 访问 PostgreSQL 数据库时,我能够成功连接。

Could someone please help - I would be much obliged.有人可以帮忙吗 - 我将非常感激。

Code:代码:

from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://<user>:<pass>@<public IP Address/<table>')

engine.connect()

Error:错误:

Is the server running on host "XX.XX.XXX.XX" and accepting
TCP/IP connections on port XXXX?

I found another way to connect to a PostgreSQL GCP instance without using the Cloud SQL Proxy.我找到了另一种不使用云 SQL 代理连接到 PostgreSQL GCP 实例的方法。

Code:代码:

import sqlalchemy

username = ''  # DB username
password = ''  # DB password
host = ''  # Public IP address for your instance
port = '5432'
database = ''  # Name of database ('postgres' by default)

db_url = 'postgresql+psycopg2://{}:{}@{}:{}/{}'.format(
    username, password, host, port, database)

engine = sqlalchemy.create_engine(db_url)

conn = engine.connect()

I whitelisted my IP address before trying to connect.在尝试连接之前,我将我的 IP 地址列入了白名单。 ( https://cloud.google.com/sql/docs/postgres/connect-external-app#appaccessIP ) https://cloud.google.com/sql/docs/postgres/connect-external-app#appaccessIP

Use the Cloud SQL proxy to connect to Cloud SQL from external applications.使用 Cloud SQL 代理从外部应用程序连接到 Cloud SQL。

In order to achieve this please follow the relevant documentation .为了实现这一点,请遵循相关文档

The steps described would consist of:描述的步骤包括:

  1. Enabling the Cloud SQL Admin API on your Cloud Console.在 Cloud Console 上启用 Cloud SQL 管理员 API。
  2. Installing the relevant proxy client according to your OS.根据您的操作系统安装相关代理客户端。
  3. Use any of the available methods to authenticate the Cloud SQL Proxy .使用任何可用方法对Cloud SQL 代理进行身份验证
  4. Invoke the proxy with ./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:5432 & ond your terminal and connect the proxy by changing your code and using SQLALCHEMY:使用./cloud_sql_proxy -instances=INSTANCE_CONNECTION_NAME=tcp:5432 & ond 调用代理并通过更改代码和使用 SQLALCHEMY 连接代理:
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://DATABASE_USER:PASSWORD@localhost:5432/')

NOTE: the code above assumes you are not trying to connect to the proxy in a production environment and are using an authenticated Cloud SDK client in order to connect to the proxy.注意:上面的代码假设您没有尝试在生产环境中连接到代理,而是使用经过身份验证的 Cloud SDK 客户端来连接到代理。

Depending on the database client library, the socket ( /cloudsql/INSTANCE_CONNECTION_NAME/.s.PGSQL.5432 ) needs to be specified.根据数据库客户端库,需要指定套接字 ( /cloudsql/INSTANCE_CONNECTION_NAME/.s.PGSQL.5432 )。

The docs have this example for SQLAlchemy :文档SQLAlchemy这个例子:

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:
    # postgresql+pg8000://<db_user>:<db_pass>@/<db_name>
    #                         ?unix_sock=<socket_path>/<cloud_sql_instance_name>/.s.PGSQL.5432
    sqlalchemy.engine.url.URL.create(
        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
)

Be aware that this example is with pg8000 that uses unix_sock instead of unix_socket as socket identifier.请注意,此示例使用pg8000 ,它使用unix_sock而不是unix_socket作为套接字标识符。

This worked to me using the Cloud SQL Proxy on my personal computer and uploading the code to Google App Engine standard.这对我有用,在我的个人计算机上使用 Cloud SQL 代理并将代码上传到 Google App Engine 标准。

db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_pass = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')
if os.environ.get('GAE_ENV') == 'standard':
    db_uri = f'postgresql+psycopg2://{db_user}:{db_pass}@/{db_name}?host=/cloudsql/{db_connection_name}'
else:
    db_uri = f'postgresql+psycopg2://{db_user}:{db_pass}@127.0.0.1:1234/{db_name}'
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = db_uri
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM