How To Setup Psycopg2 With Google App Engine Postgresql Database
Solution 1:
It is a little bit tricky, but here is what worked for me. I will help you to set up the Quickstart App Engine with psycopg2 and after that you will get the idea.
Use the Quickstart for Python in the App Engine Flexible Environment documentation to set up and deploy your app.
Use the Connecting from App Engine documentation to connect to your App Engine app to the Cloud SQL Postgre SQL.
I have did slightly modifications in order to make that work:
In 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".
In requirements.txt
add:
psycopg2
psycopg2-binary
In main.py
add:
@app.route('/connect')defconnect():
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"
Use the gcloud app deploy
command to deploy your app.
After the deployment, use the gcloud app browse
command to open the app in the browser.
When accessing the link https://[PROJECT_ID].appspot.com/connect
It should respond with Connection was established!
Post a Comment for "How To Setup Psycopg2 With Google App Engine Postgresql Database"