我有一个正在谷歌的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。我是不是漏掉了什么?
发布于 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中:
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中:
psycopg2
psycopg2-binary在main.py add中:
@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!响应
https://stackoverflow.com/questions/55391490
复制相似问题