在 Cloud Code 中使用 Cloud 客户端库

本页面介绍了如何快速开始使用 Cloud 客户端库和 Cloud Code您将使用 Hello World 示例应用,然后更新该应用以使用 Cloud Translation API 将响应翻译成西班牙语。

准备工作

  1. 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  3. 确保您的 Google Cloud 项目已启用结算功能

  4. 启用 Google Kubernetes Engine and Cloud Translation API。

    启用 API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Go to project selector

  6. 确保您的 Google Cloud 项目已启用结算功能

  7. 启用 Google Kubernetes Engine and Cloud Translation API。

    启用 API

  8. 安装 Git,以便 Cloud Code 可以执行 Git 操作,例如克隆示例。
  9. 安装 Cloud Code 插件

创建应用

  1. 在命令面板 (Cmd/Ctrl+Shift+P) 中, 运行 Cloud Code: New Application,选择 Kubernetes Application。 然后选择使用您偏好语言的 Hello World 应用。例如,选择 Node.js: Hello World:创建一个 Node.js 版 Hello World 入门应用。
  2. 保存新应用。系统会显示一条通知,确认您的应用已创建且 新窗口。

设置凭据

  1. 如需打开终端,请依次点击终端 > 新建终端

  2. 创建服务账号以对您的 API 请求进行身份验证:

    gcloud iam service-accounts create \
    translation-quickstart \
    --project PROJECT_ID
    
  3. 向您的服务账号授予 Cloud Translation API User 角色:

    gcloud projects \
    add-iam-policy-binding \
    PROJECT_ID \
    --member='serviceAccount:translation-quickstart@PROJECT_ID.iam.gserviceaccount.com' \
    --role='roles/cloudtranslate.user'
    
  4. 创建服务账号密钥:

    gcloud iam service-accounts keys \
    create key.json --iam-account \
    translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
    
  5. 将密钥设置为默认凭据:

    export \
     GOOGLE_APPLICATION_CREDENTIALS=key.json
    

从应用中调用 Cloud Translation API

Go

  1. 安装 Cloud Translation API Cloud 客户端库:

    1. 如需打开终端,请依次点击终端 > 新建终端
    2. 运行以下命令:

      go get cloud.google.com/go/translate/apiv3
      
  2. 创建 app.go 文件。

  3. 打开 app.go 并添加软件包名称、导入项和应用框架:

    package main
    
    import (
      "context"
      "fmt"
    
      translate "cloud.google.com/go/translate/apiv3"
      translatepb "google.golang.org/genproto/googleapis/cloud/translate/v3"
    )
    
    func translateText(w io.Writer, projectID string, sourceLang string, targetLang string, text string) error {
    
    }
    
    func main() {
    
    }
    
  4. translateText() 函数中,添加以下代码, 翻译指定文本。选择文件 >保存即可重新设置 代码:

    ctx := context.Background()
    client, err := translate.NewTranslationClient(ctx)
    if err != nil {
      return fmt.Errorf("NewTranslationClient: %v", err)
    }
    defer client.Close()
    
    req := &translatepb.TranslateTextRequest{
      Parent:             fmt.Sprintf("projects/%s/locations/global", projectID),
      SourceLanguageCode: sourceLang,
      TargetLanguageCode: targetLang,
      MimeType:           "text/plain", // Mime types: "text/plain", "text/html"
      Contents:           []string{text},
    }
    
    resp, err := client.TranslateText(ctx, req)
    if err != nil {
      return fmt.Errorf("TranslateText: %v", err)
    }
    
    // Display the translation for each input text provided
    for _, translation := range resp.GetTranslations() {
      fmt.Fprintf(w, "Translated text: %v\n", translation.GetTranslatedText())
    }
    
    return nil
    
  5. main() 函数中,调用 translateText()。以下 参数值将英语翻译成西班牙语:

    projectID := "<var>PROJECT_ID</var>"
    sourceLang := "en-US"
    targetLang := "es"
    text := "Text to translate"
    
    err := translateText(os.Stdout, projectID, sourceLang, targetLang, text)
    if err != nil {
      fmt.Print(err)
    }
    
  6. 从终端运行您的应用。

    go run app.go
    

Java

  1. 打开 pom.xml 并将以下代码段添加到 dependencies 部分:

    <dependencies>
      <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
      </dependency>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-translate</artifactId>
      </dependency>
    </dependencies>
    
  2. 然后,在 pom.xml 文件中,将以下代码段添加到 “dependencyManagement”部分:

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.39.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    

    确保您使用的是最新版 Google Cloud 支持 库。如需查看版本列表,请参阅 Google Cloud 支持的库

  3. 当系统询问您是否要同步 Java 类路径/配置时, 点击始终

  4. 创建一个名为 app.java 的文件。

  5. app.java 中,在软件包后面添加以下导入内容 定义:

    import com.google.cloud.translate.v3.LocationName;
    import com.google.cloud.translate.v3.TranslateTextRequest;
    import com.google.cloud.translate.v3.TranslateTextResponse;
    import com.google.cloud.translate.v3.Translation;
    import com.google.cloud.translate.v3.TranslationServiceClient;
    import java.io.IOException;
    
  6. translateText() 方法添加到您的 App 类。此方法会设置变量并将其传递给过载的 translateText() 方法。以下值会将英语翻译成西班牙语:

    public static void translateText() throws IOException {
      String projectId = "<walkthrough-project-id/>";
      String targetLanguage = "es";
      String text = "Hello world!";
      translateText(projectId, targetLanguage, text);
    }
    
  7. 添加过载的 translateText() 方法。此方法会接受文本并将其翻译成目标语言。

    public static void translateText(String projectId, String targetLanguage, String text)
      throws IOException {
    
      try (TranslationServiceClient client = TranslationServiceClient.create()) {
        LocationName parent = LocationName.of(projectId, "global");
    
        TranslateTextRequest request =
          TranslateTextRequest.newBuilder()
          .setParent(parent.toString())
          .setMimeType("text/plain")
          .setTargetLanguageCode(targetLanguage)
          .addContents(text)
          .build();
    
        TranslateTextResponse response = client.translateText(request);
    
        // Display the translation for each input text provided
        for (Translation translation : response.getTranslationsList()) {
          System.out.printf("Translated text: %s\n", translation.getTranslatedText());
        }
      }
    }
    
  8. main 中的 print 语句替换为对 translateText():

    try {
      translateText();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
    

Node.js

  1. 安装 Cloud Translation API Cloud 客户端库:

    1. 点击 Cloud Code,然后展开 Cloud API Explorer。
    2. 展开 Cloud AI,然后点击 Cloud Translation API
    3. 要安装客户端库,请点击 NodeJS,然后点击 play_arrow 在终端中运行
  2. 在项目中创建一个 app.js 文件。

  3. 打开app.js 在文件开头导入 Translation 客户端库:

    const {TranslationServiceClient} = require('@google-cloud/translate');
    
  4. 创建一个 Translation API 客户端并为您的项目 ID 添加变量, 位置和您要翻译的文本:

    // Instantiates a client
    const translationClient = new TranslationServiceClient();
    
    const projectId = 'PROJECT_ID';
    const location = 'global';
    const text = 'Hello, world!';
    
  5. 添加以下 async 函数,该函数会检测您的 Hello, world! 文本并将其翻译成西班牙语:

    async function translateText() {
        // Construct request
        const request = {
            parent: `projects/PROJECT_ID/locations/LOCATION`,
            contents: [text],
            mimeType: 'text/plain', // mime types: text/plain, text/html
            sourceLanguageCode: 'en',
            targetLanguageCode: 'es',
        };
    
        // Run request
        const [response] = await translationClient.translateText(request);
    
        for (const translation of response.translations) {
            console.log(`Translation: ${translation.translatedText}`);
        }
    }
    
  6. app.js 文件末尾调用 translateText()

    translateText();
    
  7. 要运行您的应用,请打开命令面板(按 Ctrl/Cmd + Shift + P),然后运行 Cloud Code: Run on Kubernetes

  8. 部署应用后,打开 网页视图中显示的网址。

Python

  1. 安装 Cloud Translation API Cloud 客户端库:

    1. 点击 Cloud Code,然后展开 Cloud API Explorer。
    2. 展开 Cloud AI,然后点击 Cloud Translation API
    3. 要安装客户端库,请点击 Python,然后点击 play_arrow 在终端中运行
      注意:如果您使用的是基于 Linux 的操作系统(包括 Chromebook,请将命令修改为使用 pip3,而不是 pip.如果您使用的是 Mac,请将命令更改为使用 pip3 并添加 --user 标志。
  2. 在项目中创建一个 app.py 文件。

  3. app.py 中,在文件开头导入客户端库:

    from google.cloud import translate
    
  4. 添加 translate_text 函数。这会初始化一个客户端,以便与之交互 Cloud Translation API。

    def translate_text(text="Hello, world!", project_id="PROJECT_ID"):
    
    client = translate.TranslationServiceClient()
    location = "global"
    parent = "projects/PROJECT_ID/locations/LOCATION"
    
  5. 要将文本从英语翻译成西班牙语并打印结果,请在 translate_text 函数,请将以下调用添加到 Cloud Translation API Cloud 客户端库:

       response = client.translate_text(
        request={
            "parent": parent,
            "contents": [text],
            "mime_type": "text/plain",
            "source_language_code": "en-US",
            "target_language_code": "es",
        }
    )
    
    for translation in response.translations:
        print("Translated text: {}".format(translation.translated_text))
    
  6. app.py 末尾,调用 translate_text()

    translate_text()
    
  7. 要运行您的应用,请打开命令面板(按 Ctrl/Cmd + Shift + P),然后运行 Cloud Code: Run on Kubernetes

  8. 部署应用后,打开 网页视图中显示的网址。

清理

停止应用后,此期间部署的所有 Kubernetes 资源 运行作业会自动删除

为避免系统因此 如果出现以下情况,请务必删除项目或删除您创建的集群 您希望重复使用该项目

如需删除集群,请执行以下操作:

  1. 在 Kubernetes Explorer 中,暂停一下您的集群名称,然后点击 open_in_new 在 Google Cloud 控制台中打开
  2. 点击删除,然后再次点击删除进行确认。

如需删除项目(以及关联的资源,包括所有集群),请执行以下操作:

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

    转到“管理资源”

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

获取支持

如需发送反馈,请在以下位置报告问题 GitHub、 或在 Stack Overflow

后续步骤