通过 Cloud Functions 连接到 Cloud SQL

上次更新时间:2020-06-17

什么是 Cloud SQL?

Cloud SQL 是一项全代管式数据库服务,让您能够在 Google Cloud Platform 上轻松设置、维护、管理和控制关系型数据库。

什么是 Cloud Functions?

Cloud Functions 是一个轻量级计算解决方案,可供开发者创建单一用途的独立函数,无需管理服务器或运行时环境即可对云端事件作出响应。

您将构建的内容

在此 Codelab 中,您将用 Python 编写一个 Cloud Functions 函数。函数:

  • 连接到 Cloud SQL 数据库实例。
  • 向数据库中的表发送插入语句。

您将学习的内容

  • 如何在 Google Cloud Console 中访问 Cloud Functions 网页界面。
  • 如何创建 Cloud Functions 函数。
  • 如何测试 Cloud Functions 函数。
  • 如何使用 Python 连接到 Cloud SQL 数据库实例(MySQL 或 PostgreSQL)。
  • 如何使用 Python 写入 Cloud SQL 数据库。
  • 浏览器,例如 Chrome 或 Firefox。
  • 包含您的 Cloud SQL 实例的 Google Cloud Platform 项目。
  • 如果您还没有此工具,请参阅我们提供的教程。执行除删除实例之外的所有步骤。
  • 您的实例包含一个带有表的 MySQL 或 PostgreSQL 数据库。
  • 您的实例连接名称、数据库和表名称、数据库用户名和用户的密码。
  • 具有 Cloud SQL Client 角色的服务帐号。

用于连接到 Cloud SQL 数据库的 Cloud Functions 函数代码位于此处。某些变量值取决于您的 Cloud SQL 数据库是 MySQL 还是 PostgreSQL,具体取决于您的数据库信息。

Cloud Console 中的 Cloud Functions 界面包含一个文本编辑器。 您可以将代码复制/粘贴到该编辑器中并进行修改,也可以先在本地修改代码,然后再将其复制/粘贴到界面中。

requirements.txt

# This file tells Python which modules it needs to import
SQLAlchemy==1.3.12
# If your database is MySQL, uncomment the following line:
#PyMySQL==0.9.3
# If your database is PostgreSQL, uncomment the following line:
#pg8000==1.13.2

main.py

# This file contains all the code used in the codelab.
import sqlalchemy

# Depending on which database you are using, you'll set some variables differently.
# In this code we are inserting only one field with one value.
# Feel free to change the insert statement as needed for your own table's requirements.

# Uncomment and set the following variables depending on your specific instance and database:
#connection_name = ""
#table_name = ""
#table_field = ""
#table_field_value = ""
#db_name = ""
#db_user = ""
#db_password = ""

# If your database is MySQL, uncomment the following two lines:
#driver_name = 'mysql+pymysql'
#query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})

# If your database is PostgreSQL, uncomment the following two lines:
#driver_name = 'postgres+pg8000'
#query_string =  dict({"unix_sock": "/cloudsql/{}/.s.PGSQL.5432".format(connection_name)})

# If the type of your table_field value is a string, surround it with double quotes.

def insert(request):
    request_json = request.get_json()
    stmt = sqlalchemy.text('insert into table_name (table_field) values (table_field_value)')

    db = sqlalchemy.create_engine(
      sqlalchemy.engine.url.URL(
        drivername=driver_name,
        username=db_user,
        password=db_password,
        database=db_name,
        query=query_string,
      ),
      pool_size=5,
      max_overflow=2,
      pool_timeout=30,
      pool_recycle=1800
    )
    try:
        with db.connect() as conn:
            conn.execute(stmt)
    except Exception as e:
        return 'Error: {}'.format(str(e))
    return 'ok'
  1. 在浏览器中,转到 Google Cloud Platform Console 界面。
  2. 从导航菜单中选择 Cloud Functions。
  3. 点击按钮栏上的创建函数。
  4. 为函数输入一个名称。
  5. 选择 HTTP 触发器。(请记下触发器项下方显示的网址。此格式如下:https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME)
  6. 为“源代码”选项选择内嵌编辑器。
  7. 为“运行时”选项选择 Python 3.7。
  8. 在源代码编辑器窗口中,删除 requirements.txt 和 main.py 的现有内容,并将它们替换为上述代码的修改版本。
  9. 输入 insert 作为“要执行的函数”的名称。
  10. 在高级选项中,选择具有 Cloud SQL Client 角色的服务帐号。
  11. 点击创建,然后等待旋转图标停止。当该函数可供使用时,会出现一个绿色对勾标记。
  1. 在浏览器中,转到 Google Cloud Platform Console 界面。
  2. 从导航菜单中选择 Cloud Functions。
  3. 点击您之前创建的函数的名称。
  4. 选择页面中间的测试链接。
  5. 选择测试函数。
  6. 结果应显示:正常(如果测试失败,系统会显示一条堆栈轨迹以帮助进行调试。)
  7. 在浏览器中,转到您之前在创建该函数时保存的网址。
  8. 正常结果也应该会显示在浏览器中。

恭喜,您已成功构建一个可与 Cloud SQL 搭配使用的 Cloud Functions 函数。

具体来说,您创建了一个 Cloud Functions 函数,用于连接 Cloud SQL 数据库实例并向其写入数据。

查看其中一些 Codelab...

更多详情

参考文档