When using Google Appengine Flexible + Python, how to use Psycopg2 directly (without SQLAlchemy) to access a CloudSQL PostgreSQL database?
Hello myselfhimself
,
Here is a solution:
app.yaml
, add an environment variable, imitating Google Appengine Flexible Python CloudSQL documentation's SQLAlchemy's URI but without the psycopg2+
prefix:env_variables: PSYCOPG2_POSTGRESQL_URI: postgresql://user:password@/databasename?host=/cloudsql/project-name:region:database-instance-name
psycopg2
's connect
statement directly. This leverages psycopg2.connect
's ability to pass the URI directly to the psql
client library (this might not work with older PostgreSQL versions..).import os import psycopg2 conn = psycopg2.connect(os.environ['PSYCOPG2_POSTGRESQL_URI'])
app.yaml
:export PSYCOPG2_POSTGRESQL_URI="postgresql://user:password@/databasename?host=/cloudsql/project-name:region:database-instance-name" ./cloud_sql_proxy -instances=project-name:region:database-instance-name=tcp:5432 #somewhat later: python myserver.py
I hope it will work for your too : )