Det er en lille smule tricky, men her er hvad der virkede for mig. Jeg hjælper dig med at opsætte Quickstart App Engine med psycopg2, og derefter får du ideen.
Brug Quickstart for Python i App Engine Flexible Environment dokumentation for at konfigurere og implementere din app.
Brug Opret forbindelse fra App Engine dokumentation for at oprette forbindelse til din App Engine-app til Cloud SQL Postgre SQL.
Jeg har lavet små ændringer for at få det til at virke:
I app.yaml
tilføje:
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".
I requirements.txt
tilføje:
psycopg2
psycopg2-binary
I main.py
tilføje:
@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"
Brug gcloud app deploy
kommando for at implementere din app.
Efter implementeringen skal du bruge gcloud app browse
kommando for at åbne appen i browseren.
Når du får adgang til linket https://[PROJECT_ID].appspot.com/connect
Det skulle svare med Connection was established!