How can I use flask-sqlalchemy with Google Cloud Functions?

Viewed 1924

How can I integrate flask-sqlalchemy with Google Cloud Functions and something like Cloud SQL?

Looking at the minimal application example, it wraps the app variable:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

But my Google Cloud Function doesn't have access to anything called app:

def my_function(request):
    return "Hello world!"

Creating my own app with app = Flask(__name__) doesn't work as this app isn't used by Cloud Functions to return the response.

1 Answers

You can use flask.current_app instead. You'll also have to configure flask-sqlalchemy to use the Unix Domain Socket provided by CloudSQL:

from flask import current_app as app
from flask_sqlalchemy import SQLAlchemy

# Set these in the environment variables for the function
db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_password = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')

# This is for Postgres, it's similar for MySQL
app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{db_user}:{db_password}@/{db_name}?host=/cloudsql/{db_connection_name}'

# This must be set, determine which is best for you
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
...

Then you can query the User model in your function:

def my_function(request):
    user = User.query.first()
    return f"Hello {user.username)!"
Related