0

I am new to Google cloud. My application is build with python FastAPI with alembic migrations. I am looking for the best way to connect to Google cloud SQL with alembic to run my migrations. Thanks. Please share sample code.

Trying to connect using Google cloud python connector but fail

  • How are you deploying your application? A common way of doing this is part of application / container startup. – MatsLindh May 31 '23 at 09:07
  • I am deploying using docker image. But right now the problem is how to modify the alembic eny.py to be able to use the cloud SQL python connector. – LARTEY JOSHUA May 31 '23 at 09:59
  • I have not tried Alembic but FastAPI does work with Cloud SQL Python Connector, see https://github.com/jackwotherspoon/cloud-sql-fastapi for examples. – Jack Wotherspoon Jun 01 '23 at 14:07
  • Yes, I was able to use the Cloud SQL Python Connector in production after running the migrations. Thanks – LARTEY JOSHUA Jun 05 '23 at 12:11

1 Answers1

3

I was able to find out how to connect to google cloud SQL using FASTAPI and Alembic for migration. Follow the steps.

  1. Ensure Google Cloud SQL Admin and Google Cloud Auth Proxy are enabled for your Project.
  2. Follow the link to download Google Cloud Auth Proxy https://cloud.google.com/sql/docs/mysql/connect-auth-proxy#windows-64-bit. Ensure you choose the right environment.
  3. Open Power shell and navigate to the folder where your downloaded Google Cloud Auth Proxy
  4. Run this command on the power shell ./cloud-sql-proxy --address 0.0.0.0 --port 1234 INSTANCE_CONNECTION_NAME
  5. you should see the following log on the power shell.

Logs from power Shell

  1. Now use the MySQL connection url (mysql+pymysql://user:password@localhost:1234/database_name) to connect in your FastAPI and Alembic eny.py. Take note of the port.

7. Finally, run your migrations and your FastAPI app.

  • I recommend that you only use the address `localhost` or `127.0.0.1` instead of `0.0.0.0`. Otherwise, anyone on your local network (local firewall permitting) can connect to the proxy. – John Hanley May 31 '23 at 16:48