首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Google App Engine PostgreSQL数据库设置psycopg2

如何使用Google App Engine PostgreSQL数据库设置psycopg2
EN

Stack Overflow用户
提问于 2019-03-28 14:35:49
回答 1查看 1K关注 0票数 1

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

代码语言:javascript
复制
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。我是不是漏掉了什么?

EN

Stack Overflow用户

发布于 2019-03-28 18:35:56

这有点棘手,但这是对我有用的。我将帮助您设置快速入门应用程序引擎与psycopg2,然后您将得到的想法。

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

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

为了让它工作,我做了一些细微的修改:

app.yaml add中:

代码语言:javascript
复制
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 add中:

代码语言:javascript
复制
psycopg2
psycopg2-binary

main.py add中:

代码语言:javascript
复制
@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!响应

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55391490

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档