【问题标题】:How to setup psycopg2 with Google App Engine PostgreSQL database如何使用 Google App Engine PostgreSQL 数据库设置 psycopg2
【发布时间】:2019-03-28 18:35:56
【问题描述】:

我有一个在 Google 的 App Engine 上运行的应用程序,我希望它使用关联的 PostgreSQL 数据库。我正在使用 psycopg2 来帮助我进行 SQL 查询。但是我不确定如何设置连接。这是我目前拥有的:

con = psycopg2.connect(
    host=HOST_NAME, # the IP address of the SQL database
    database=DATABASE_NAME, # the name of the database (I'm using the default, so this is "postgres"
    user=USER_NAME, # just the user name that I created
    password=PASSWORD # the password associated to that user
)

但是,当我尝试发出请求时,我在创建此连接时收到错误 psycopg2.OperationalError: could not connect to server: Connection timed out。有什么我想念的吗?

【问题讨论】:

    标签: python postgresql google-app-engine psycopg2


    【解决方案1】:

    这有点棘手,但这对我有用。我将帮助您使用 psycopg2 设置 Quickstart App Engine,然后您就会明白。

    使用Quickstart for Python in the App Engine Flexible Environment 文档来设置和部署您的应用。

    使用 Connecting from App Engine 文档将您的 App Engine 应用连接到 Cloud SQL Postgre SQL。

    为了让它发挥作用,我做了些许修改:

    app.yaml 中添加:

    beta_settings:
      cloud_sql_instances: [INSTANCE_CONNECTION_NAME]=tcp:5432
    #[INSTANCE_CONNECTION_NAME] = [PROJECT_NAME]:[INSTANCE_ZONE]:[INSTANCE_NAME]
    #[INSTANCE_CONNECTION_NAME] can be found at Google Cloud Console Cloud SQL's instance page, under "Instance connection name".
    

    requirements.txt 中添加:

    psycopg2
    psycopg2-binary
    

    main.py 添加:

    @app.route('/connect')
    def connect():
        try:
            #host='172.17.0.1' is the defult IP for the docker container that it is being created during the deployment of the App Engine
            conn = psycopg2.connect("dbname='postgres' user='postgres' host='172.17.0.1' password='test'")
            return "Connection was established!"
        except:
            return "I am unable to connect to the database"
    

    使用gcloud app deploy 命令部署您的应用。

    部署完成后,使用gcloud app browse命令在浏览器中打开应用。

    访问链接时https://[PROJECT_ID].appspot.com/connect 它应该回复Connection was established!

    【讨论】:

    • 我尝试了您在此处所述的步骤,但我仍然收到连接超时错误。 host 应该是 sql 实例的公共 IP 地址还是总是 172.17.0.1
    • 我已经尝试了上述所有步骤,它们对我有用。是的,它将始终为 172.17.0.1,因为您使用的是 app.yaml 文件中的 Cloud SQL 代理设置。因此,您必须连接到默认生成的容器的默认 IP 地址和端口。我建议从头开始再次启动相同的过程,使用新的 App Engine Python 应用创建一个新的 SQL 实例。然后看看差异。
    猜你喜欢
    • 2020-11-22
    • 2011-07-03
    • 2022-07-26
    • 2020-12-25
    • 1970-01-01
    • 2018-02-06
    • 2018-08-30
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多