What's the easiest way to create a Cloud Function and PostgreSQL instance?

I have tied using gcloud CLI for setting up network and am getting lost there. I expect it must be easier than what I am trying right now. How would you create a minimalistic Python function talking to a Postgres database?

1 2 66
2 REPLIES 2

Ah, nevermind - I've learnt how to use the connector package and it's not that bad

 

import json
import os

from google.cloud.sql.connector import Connector, IPTypes


def handler(request, **kwargs):
conn = Connector().connect(
os.environ['DB_CONNECTION'],
"pg8000",
user=os.environ['DB_USER'],
password=os.environ['DB_PASSWORD'].strip(),
db=os.environ['DB_DATABASE'],
ip_type=IPTypes.PUBLIC,
)
cur = conn.cursor()
cur.execute('SELECT tablename FROM pg_catalog.pg_tables')
rows = cur.fetchall()
cur.close()
conn.close()

return str(len(rows))