Establishes a database connection to a Cloud SQL for PostgreSQL instance using a Unix socket. It utilizes the SQLAlchemy library to create a connection engine, configured specifically for the pg8000 driver. The script retrieves necessary connection parameters like database user, password, database name, and the Unix socket path from environment variables. This approach is particularly useful for applications running in the same Google Cloud region as the Cloud SQL instance, offering a secure and efficient way to communicate with the database without needing to configure IP allowlisting for TCP connections.
Explore further
For detailed documentation that includes this code sample, see the following:
- About connection options
- Connect from App Engine flexible environment
- Connect from App Engine standard environment
- Connect from Cloud Build
- Connect from Cloud Run
- Connect from Cloud Run functions
- Connect using the Cloud SQL Auth Proxy
- Manage database connections
Code sample
Python
To authenticate to Cloud SQL for PostgreSQL, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.
What's next
To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.