How to connect cloud function to cloudsql

Viewed 1167

How I can connect cloud function to cloudsql.

import psycopg2
def hello_gcs(event, context):

    print("Imported")
    conn = psycopg2.connect("dbname='db_bio' user='postgres' host='XXXX' password='aox199'")
    print("Connected")   
    file = event
    print(f"Processing file: {file['name']}.")

Could not connect to cloud sql's postgres version, please help.

2 Answers

Google Cloud Function provides a unix socket to automatically authenticate connections to your Cloud SQL instance if it is in the same project. This socket is located at /cloudsql/[instance_connection_name].

conn = psycopg2.connect(host='/cloudsql/[instance_connection_name]', dbname='my-db', user='my-user',  password='my-password')

You can find the full documentation page (including instructions for authentication from a different project) here.

Related