Charlie Morton
Charlie Morton

Reputation: 787

Google App Engine connect to Cloud SQL postgres

I have a flask application which I can run locally fine using flask_sqlalchemy with a SQLITE DB.

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'

I am now deploying this to Google App Engine. I have created a postgres db in CloudSQL.

How can I connect to the cloudsql database?

Upvotes: 1

Views: 584

Answers (1)

Chris32
Chris32

Reputation: 4961

You don't specify if you are using the standard or the flex environment in App engine but in general to connect Cloud SQL Postgres to App Engine you can use the sqlalchemy library.

Code for reference extracted from the Public Documentation. The complete version can be found in the Cloud Platform GitHub

# The SQLAlchemy engine will help manage interactions, including automatically
# managing a pool of connections to your database
db = sqlalchemy.create_engine(
    # Equivalent URL:
    # postgres+pg8000://<db_user>:<db_pass>@/<db_name>?unix_sock=/cloudsql/<cloud_sql_instance_name>/.s.PGSQL.5432
    sqlalchemy.engine.url.URL(
        drivername='postgres+pg8000',
        username=db_user,
        password=db_pass,
        database=db_name,
        query={
            'unix_sock': '/cloudsql/{}/.s.PGSQL.5432'.format(
                cloud_sql_connection_name)
        }
    ),
    # ... Specify additional properties here.
    # ...
)

Upvotes: 2

Related Questions