如何将flask-sqlalchemy与Google Cloud Functions结合使用?

时间:2018-12-17 20:50:43

标签: python python-3.x flask google-cloud-platform google-cloud-functions

如何将flask-sqlalchemy与Google Cloud Functions和Cloud SQL之类的东西集成?

看着minimal application example,它包装了app变量:

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

但是我的Google Cloud Function无法访问称为app的任何内容:

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

使用app = Flask(__name__)创建自己的应用无法正常工作,因为Cloud Functions并未使用此应用来返回响应。

1 个答案:

答案 0 :(得分:2)

您可以改用flask.current_app。您还必须配置flask-sqlalchemy才能使用CloudSQL提供的Unix域套接字:

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)
...

然后,您可以在函数中查询User模型:

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