如何将flask-sqlalchemy
与Google Cloud功能集成以及类似Cloud SQL?
查看最小应用示例,它包含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云功能无法访问任何称为app
的内容:
def my_function(request):
return "Hello world!"
使用app = Flask(__name__)
创建自己的应用程序不起作用,因为云功能不使用此应用来返回响应。
您可以改用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)!"