我如何使用Google Cloud功能使用Blask-Sqlalchemy



如何将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)!"

相关内容

  • 没有找到相关文章

最新更新