I created a google function to connect to Mysql, I created the database using Cloud SQL. I gave it Cloud permissions.
Here’s the code inside my 1st gen function (main.py). Please keep in mind “” actually have my keys
import os
from google.cloud.sql.connector import Connector, IPTypes
import pymysql
import sqlalchemy
def connect_with_connector() -> sqlalchemy.engine.base.Engine:
"""
Initializes a connection pool for a Cloud SQL instance of MySQL.
Uses the Cloud SQL Python Connector package.
"""
instance_connection_name = os.environ[
""
] # 'project:region:instance'
db_user = os.environ[""] # 'my-db-user'
db_pass = os.environ[""] # 'my-db-password'
db_name = os.environ[""] # 'my-database'
ip_type = IPTypes.PRIVATE if os.environ.get("PRIVATE_IP") else IPTypes.PUBLIC
connector = Connector(ip_type)
def getconn() -> pymysql.connections.Connection:
conn: pymysql.connections.Connection = connector.connect(
instance_connection_name,
"pymysql",
user=db_user,
password=db_pass,
db=db_name,
)
return conn
pool = sqlalchemy.create_engine(
"mysql+pymysql://",
creator=getconn,
# ...
)
return pool
As entry point I have ‘connect_with_connector’
On requierements.txt I have
google-cloud-sql-connector
pymysql
sqlalchemy
I followed this documentation
https://cloud.google.com/sql/docs/mysql/connect-functions
There’s not important information on logs.