在 Gemini 的帮助下开发 Python 应用

本教程介绍如何使用 Google Cloud 中的 Gemini(Google Cloud 中 AI 赋能的协作工具)探索、创建、修改、测试和部署示例 Python 应用。

在下面的示例中,假设您是一名开发者,您属于正在开发 Inventory 应用的团队。您负责为基本服务进行原型设计,该服务包含一些可作为商品目录应用的一部分运行的 API 方法。您希望在本地 VS Code 环境中开发应用,然后将其部署到 Google Cloud。但是,您不确定哪项 Google Cloud 服务最适合您的使用场景。

在本教程中,您将使用 Gemini 和 Visual Studio Code 作为 IDE 来构建具有两种 API 方法的示例 Inventory 应用。

本教程适用于协助构建应用但可能不熟悉云技术的任何经验水平的开发者。本文假定您具备将 VS Code 用作 IDE 的经验,并且熟悉 Python 和 Flask 框架。

目标

  • 通过提出 Gemini 情境问题,探索可用于部署应用的各种 Google 服务。

  • 提示 Gemini 提供可用于在 Cloud Run 中开发基本 Python 应用的模板。

  • 使用 Gemini 说明并生成代码,以创建、探索和修改应用。

  • 在本地运行并测试应用,然后使用 Gemini 生成相关步骤将其部署到 Google Cloud。

使用的 Google Cloud 产品

本教程使用以下可计费的 Google Cloud 产品。 请使用价格计算器根据您的预计使用情况来估算费用。

  • Cloud Run:Cloud Run 是一个代管式计算平台,可让您直接在 Google 可伸缩的基础架构上运行容器。如果您可以从 Cloud Run 构建容器映像,则可以将其部署在 Cloud Run 上以任何编程语言编写的代码。如需了解价格信息,请参阅 Cloud Run

除了前面提到的产品之外,本教程还使用了以下产品:

  • 双子座。Gemini 是 Google Cloud 中始终在线的协作工具,为广大用户(包括开发者和数据科学家)提供由生成式 AI 赋能的协助。为了提供集成式协助体验,Gemini 已嵌入到许多 Google Cloud 产品中。

  • Cloud Code for VS Code 扩展程序。此扩展程序是一个 IDE 插件,可为 Kubernetes 和 Cloud Run 应用的开发周期提供支持。如需详细了解 Cloud Code 扩展程序,请参阅 Cloud Code for VS Code 功能

准备工作

  1. 安装 VS Code 的本地副本(如果尚未安装)。

  2. 安装适用于 VS Code 的 Cloud Code 扩展程序

    按照安装指南中的说明安装 PythonGitDocker 客户端。此外,还要按照相应步骤创建 Google Cloud 项目。

  3. 确保已为您的 Google Cloud 用户账号和项目设置了 Gemini。
  4. 为您的 IDE 启用 Gemini。

    按照步骤在 IDE 中连接到 Google Cloud,并选择为 Google Cloud 设置的项目。

探索 Google Cloud 服务

如果您刚开始接触 Google Cloud,Gemini 可以帮助您选择符合应用架构要求的 Google Cloud 服务。

在 IDE 中,您可以通过与 Gemini 聊天来获取帮助。在 Gemini 窗格中输入提示(描述您所需要的帮助的问题或语句),Gemini 会返回“回复”。提示可以包含现有代码中的上下文,Google Cloud 会分析这些上下文,以提供更实用或更完整的响应。如需详细了解如何撰写提示以生成优质回复,请参阅为 Gemini 撰写更好的提示

如需向 Gemini 提示有关 Google Cloud 服务的信息,请按以下步骤操作:

  1. 在 IDE 的活动栏中,点击 spark Gemini

    如需找到 VS Code 的活动栏,请参阅界面

  2. Gemini 窗格中,输入以下提示,然后点击 Send

    I am new to Google Cloud and I want to use the Cloud Code extension.
    Give me some examples of Google services that I can use to build and deploy a
    sample app using containers.
    

    Gemini 会返回 Google Cloud 服务列表和说明。

    在此示例中,假设 Gemini 建议将 Cloud Run 和 Cloud Functions 作为两项 Google Cloud 服务来帮助您构建和部署示例应用,但您需要有关这些服务的更多信息。

    Gemini 不会将您的提示或其回答作为数据来训练模型。如需了解详情,请参阅 Gemini for Google Cloud 如何使用您的数据

  3. 输入后续问题,例如:

    What is the difference between Cloud Run and Cloud Functions? Explain to me
    in simple terms as I am new to Google Cloud.
    

    Gemini 会在回复中说明这两项 Google Cloud 服务之间的详细差异。

  4. 可选:如需重置聊天记录,请在 Gemini 窗格中点击 delete 重置聊天

创建 Hello World Python 应用

假设您要使用 Cloud Run 创建和部署基本 Python 应用。由于您不熟悉 Cloud Run 和 Cloud Code,因此您需要有关创建应用的步骤方面的帮助。在本部分中,您将提示 Gemini 获得在 Cloud Run 中构建 Hello World Python 应用的帮助。

  1. 启动 IDE(如果尚未启动)。

  2. 在 IDE 的活动栏中,点击 spark Gemini

  3. Gemini 窗格中,输入以下提示,然后点击 Send

    How to create a new Cloud Run app in Cloud Code using the command palette?
    What languages are supported?
    

    VS Code 中的命令面板提供了所有命令的列表,包括 Cloud Code 的命令。

    输出类似于以下内容:

    To create a new Cloud Run app in Cloud Code using the command palette,
    follow these steps:
    1. Open the command palette (press Ctrl/Cmd+Shift+P or click View > Command Palette).
    2. Run the "Cloud Code: New Cloud Run App" command.
    ...
    

    Gemini 还会显示 Cloud Run 应用支持的语言。

    对于此示例,您可以选择使用基于 Python 的 Cloud Run 模板来创建示例应用。

  4. 如需了解如何通过 Cloud Run 模板创建 Python 应用,请输入以下提示:

    How do I create a Python app from a Cloud Run template using the
    command palette? I am using Cloud Code.
    

    输出类似于以下内容:

    To create a Python app from a Cloud Run template using the command palette,
    follow these steps:
    
    1. Open Cloud Code.
    
    2. Click the Command Palette
       (press Ctrl/Cmd+Shift+P or click View > Command Palette).
    
    3. Run the "Cloud Code: New Application" command.
    
    ...
    

    完成 Gemini 在其响应中提供的步骤,在 Cloud Run 中创建基本的 Hello World Python 应用。您也可以参阅下一部分,了解如何创建 Hello World Python 应用。

创建 Hello World Python 应用的备选步骤

  1. 启动 IDE(如果尚未启动)。

  2. 打开命令面板:按 Command+Shift+P(适用于 MacOS)或 Ctrl+Shift+P(适用于 Windows 和 Linux)。

  3. 在命令面板字段中,输入 Cloud Code: New Application,然后点击结果。

  4. 从可用示例列表中,选择 Cloud Run application

  5. 从可用模板列表中,选择 Python (Flask): Cloud Run

  6. 将新应用保存到您偏好的位置。

系统会显示一条通知,确认应用已创建。 系统会在 IDE 中打开所选服务的 README 文件的预览,如图 1 所示:

屏幕截图
图 1 为在 Cloud Run 中创建的 Hello World Python 应用显示的 README 文件。

探索 Hello World Python 应用

现在,您已在 Cloud Run 中创建 Hello World 应用,接下来可以使用 Gemini 说明 IDE 中部署的文件和代码段。如需浏览您创建的示例应用的代码,请按以下步骤操作:

  1. 启动 IDE。

  2. 打开资源管理器:按 Command+Shift+E(适用于 MacOS)或 Ctrl+Shift+E(适用于 Windows 和 Linux)。

    您可以看到与示例应用相关的文件。

  3. 在文件列表中,点击 Dockerfile 以显示其内容。

  4. 选择 Dockerfile 的全部内容,点击灯泡图标,然后点击 Explain this,如图 2 所示:

    dockerfile 的屏幕截图
    图 2. 选择代码后,即可使用代码说明功能。

    Gemini 会用自然语言生成有关 Dockerfile 内容和功能的解释。如果您不确定回答中的某些内容,可以提出后续问题。

  5. 如需详细了解 Dockerfile 中提到的 app.py 文件,请在 Gemini 窗格中输入以下提示:

    What is the function of the app.py file in Dockerfile?
    

    Gemini 会生成类似于以下内容的回答:

    The app.py file is the entrypoint for the container. It is the file that
    will be executed when the container is launched. In this case, the app.py
    file will run the Python code that is contained within it.
    

    或者,您也可以选择 Dockerfile 中的文本 app.py,点击灯泡图标,然后点击 Explain this

  6. 打开探索器:按 Command+Shift+E(适用于 MacOS)或 Ctrl+Shift+E(适用于 Windows 和 Linux)。

  7. 打开 app.py 文件。 您会看到两个变量:K_SERVICEK_REVISION

  8. 如需详细了解 app.py 文件中的变量,请在 Gemini 窗格中输入以下提示:

    What is the function of `K_SERVICE` and `K_REVISION` in the `app.py` file?
    

    或者,您也可以选择 Dockerfile 中的以下文本,点击灯泡图标,然后点击说明此内容

    service = os.environ.get('K_SERVICE', 'Unknown service')
    revision = os.environ.get('K_REVISION', 'Unknown revision')
    

    响应类似于以下示例:

    The code above is using the os.environ module to get the values of the
    K_SERVICE and K_REVISION environment variables. These variables are set by
    Cloud Run when it deploys the service, and they contain the name of the
    service and the revision number, respectively.
    ...
    

为应用生成示例数据

您在 Cloud Run 中创建了一个基本的 Flask 应用。您需要一个包含示例商品目录商品列表的文件,然后才能添加用于构建 Inventory 应用的功能。如需使用 Gemini 生成相关示例数据,请按以下步骤操作:

  1. 如需显示与示例应用相关的文件,请在 IDE 中点击探索器图标。

  2. 点击 New file 图标,然后创建一个名为 inventory.py 的文件。

  3. 若要让 Gemini 生成示例数据,请在 Gemini 窗格中输入以下提示:

    Create a variable called inventory which is a list of 3 JSON objects.
    Each JSON object has 2 attributes: productid and onhandqty.
    Both attributes are strings.
    

    Gemini 为三个 JSON 对象生成示例代码。

  4. 在响应中,点击 addInsert in current file,将代码示例插入 inventory.py 文件中,如图 3 所示:

    插入代码
    图 3.您可以插入 Gemini 回答中的代码。

    inventory.py 文件类似于以下内容:

    inventory = [
       {
          "productid": "12345",
          "onhandqty": "10"
       },
       {
          "productid": "23456",
          "onhandqty": "20"
       },
       {
          "productid": "34567",
          "onhandqty": "30"
       }
    ]
    

    您已成功创建 inventory.py 文件,其中包含商品目录商品列表。

修改 Hello World Python 应用

创建 inventory.py 文件后,您现在将在 app.py 文件中引入一些可对商品目录数据执行操作的 API 方法。为完成此目标,您可以使用 Gemini 中的代码生成功能。

  1. 如需显示与示例应用相关的文件,请在 IDE 中点击探索器图标。

  2. 如需显示内容,请点击 app.py 文件。

  3. 修改 import 语句,使 app.py 文件包含 inventory.py 文件:

    import os
    from flask import Flask, render_template
    from inventory import inventory
    
  4. 若要让 Gemini 为第一个 API 方法生成代码,请在 app.py 文件中输入以下注释,然后按 Ctrl+Enter

     # Generate an app route to display a list of inventory
     # items in the JSON format from the
     # inventory.py file. Use the GET method.
    
    

    Gemini 会在 app.py 文件中生成回复。

    使用 Gemini 生成代码的键盘快捷键可能与本教程使用的 Ctrl+Enter 组合不同,具体取决于系统配置。

  5. 将指针悬停在响应的任何部分上。

    系统随即会显示 Gemini 工具栏。

    Gemini 可能会生成多个回答。 在工具栏中,您可以使用 <> 键循环显示每条响应。在以下示例中,Gemini 仅生成一条响应,如图 4 所示:

    接受代码
    图 4.您可以接受 Gemini 提供的代码建议。
  6. 若要接受建议的代码示例,请点击工具栏中的 Accept

    输出类似于以下内容:

    # Generate an App route to display a list of inventory
    # items in the JSON format from the
    # inventory.py file. Use the GET method.
    @app.route('/inventory', methods=['GET'])
    def get_inventory():
        """Return a list of inventory items."""
        return jsonify(inventory)
    
  7. 可选:如需详细了解 jsonify(inventory) 函数,请突出显示相应术语并提示 Gemini 向您解释代码。

  8. 修改 import 语句,使 app.py 文件包含 jsonify 函数:

    import os
    from flask import Flask, render_template, jsonify
    from inventory import inventory
    
  9. 如需添加其他 API 方法,请在 app.py 文件中输入以下提示,然后按 Ctrl+Enter

    # Generate an App route to get an inventory item
    # given the productid. Use the GET method.
    # If there is an invalid productid,
    # display a 404 error.
    

    Gemini 会在 app.py 文件中生成回复。

  10. 将指针悬停在响应的任何部分上。

    系统随即会显示 Gemini 工具栏。

  11. 若要接受某个建议的代码示例,请点击工具栏中的 Accept(接受)。

    输出类似于以下内容:

    # Generate an App route to get an inventory item
    # given the productid. Use the GET method.
    # If there is an invalid productid,
    # display a 404 error.
    @app.route('/inventory/<productid>', methods=['GET'])
    def get_inventory_item(productid):
        """Return an inventory item given the productid."""
        for item in inventory:
            if item["productid"] == productid:
               return jsonify(item)
        return jsonify({"error": "Item not found"}), 404
    

    您已成功添加两个用于创建 Inventory 应用的 API 方法。

从 IDE 在本地运行应用

您已准备好从 VS Code 在本地部署应用。如需部署应用,请按以下步骤操作:

  1. 启动 IDE(如果尚未启动)。

  2. 在 IDE 的活动栏中,点击 spark Gemini

  3. Gemini 窗格中,输入以下提示,然后点击 Send

    How do I run a Cloud Run app locally within Cloud Code?
    Is there an emulator?
    

    按照 Gemini 响应中的步骤,从 VS Code 在本地运行应用。您也可以参阅下一部分,从 VS Code 中本地部署示例 Cloud Run 应用。

从 IDE 在本地运行应用的备选步骤

如果您未按照上一部分中的 Gemini 响应步骤操作,则可以按照以下步骤部署示例应用:

  1. 启动 IDE。

  2. 打开命令面板:按 Command+Shift+P(适用于 MacOS)或 Ctrl+Shift+P(适用于 Windows 和 Linux)。

  3. 在命令面板字段中,输入 Run on Cloud Run Emulator,然后点击结果。

  4. Build 环境文件中,保留默认值,然后点击 Run

    本教程使用 Docker 作为构建器选项。

    在 IDE 的 Output 窗格中,您可以查看构建进度。实际部署过程可能需要一些时间才能完成。

    Starting to run the app using configuration 'Cloud Run:
    Run/Debug Locally' from .vscode/launch.json...
    To view more detailed logs, go to Output channel : "Cloud Run: Run/Debug Locally - Detailed"
    Dependency check started
    Dependency check succeeded
    Starting minikube, this may take a while......
    ...
    

如需查看实际应用,请在部署完成后点击输出窗格中的网址。对于 VS Code 的本地副本,如果您指定了 localhost 8080,您的示例应用位于网址 http://localhost:8080 处。

测试两种 API 方法

如果您的示例应用已发布,您还可以检查两个应用路由是否正常运行。在此示例中,假设应用网址为 http://localhost:8080

  1. 如需查看应用的示例着陆页,请访问 http://localhost:8080

  2. 如需获取所有商品目录商品的列表,请转到 http://localhost:8080/inventory

    app.py 文件中,使用 @app.route('/inventory', methods=['GET']) 函数列出所有商品目录商品。

  3. 如需显示按 productid 属性过滤的特定商品目录商品,请点击 http://localhost:8080/inventory/productid

    例如 http://localhost:8080/inventory/1,其中 productid 等于 1。

    app.py 文件中,如需按 productid 属性显示特定的商品目录商品,会使用函数 @app.route('/inventory/<productid>', methods=['GET'])

将 Cloud Run 应用部署到 Google Cloud

现在,您可以将 Cloud Run 应用部署到 Google Cloud。您可以提示 Gemini 为您提供相关步骤,也可以按照以下步骤操作:

  1. 打开命令面板:按 Command+Shift+P(适用于 MacOS)或 Ctrl+Shift+P(适用于 Windows 和 Linux)。

  2. 在命令面板字段中,输入 Cloud Code: Deploy to Cloud Run,然后点击结果。

  3. 服务设置窗格中,设置您的 Google Cloud 项目。

  4. 接受其余的默认设置,然后点击部署

  5. Cloud Code 会构建您的映像,将其推送到注册表,并将您的服务部署到 Cloud Run。

  6. 如需查看正在运行的服务,请打开部署到 Cloud Run 对话框中显示的网址。

    您还可以按照测试两种 API 方法中的步骤查看 Google Cloud 中的示例应用。请相应调整您的网址。

清理

为避免系统因本教程中使用的资源向您的 Google Cloud 帐号收取费用,您可以删除为本教程创建的 Google Cloud 项目。或者,您也可以逐个删除资源。

  1. 在 Google Cloud 控制台中,进入管理资源页面。

    转到“管理资源”

  2. 在项目列表中,选择要删除的项目,然后点击删除
  3. 在对话框中输入项目 ID,然后点击关闭以删除项目。

后续步骤