在 Cloud Code 中使用 Cloud 客户端库
本页面介绍了如何快速开始使用 Cloud 客户端库和 Cloud Code。您将使用 Hello World 示例应用设置一个新的 Kubernetes 应用,然后更新该应用以使用 Cloud Translation API 将响应翻译成西班牙语。
准备工作
- 登录您的 Google Cloud 账号。如果您是 Google Cloud 新手,请创建一个账号来评估我们的产品在实际场景中的表现。新客户还可获享 $300 赠金,用于运行、测试和部署工作负载。
-
在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目。
-
启用 Google Kubernetes Engine and Cloud Translation API。
-
在 Google Cloud Console 中的项目选择器页面上,选择或创建一个 Google Cloud 项目。
-
启用 Google Kubernetes Engine and Cloud Translation API。
- 安装 Git,以便 Cloud Code 可以执行 Git 操作,例如克隆示例。
- 安装 Cloud Code 插件(如果尚未安装)。
创建应用
- 在命令面板 (
Cmd
/Ctrl
+Shift
+P
) 中,运行 Cloud Code: New Application(Cloud Code:新应用),选择 Kubernetes Application(Kubernetes 应用),然后选择一个采用您首选语言的 Hello World 应用。例如,选择 Node.js: Hello World 以创建 Node.js 版 Hello World 入门应用。 - 保存新应用。系统会显示一条通知,确认您的应用已创建,并打开一个显示您的应用的新窗口。
设置凭据
如需打开一个终端,请依次点击终端 > 新建终端。
创建服务账号以对您的 API 请求进行身份验证:
gcloud iam service-accounts create \ translation-quickstart \ --project PROJECT_ID
向您的服务账号授予 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'
创建服务账号密钥:
gcloud iam service-accounts keys \ create key.json --iam-account \ translation-quickstart@PROJECT_ID.iam.gserviceaccount.com
将密钥设置为默认凭据:
export \ GOOGLE_APPLICATION_CREDENTIALS=key.json
在您的应用中调用 Cloud Translation API
Go
安装 Cloud Translation API Cloud 客户端库:
- 如需打开一个终端,请依次点击终端 > 新建终端。
运行以下命令:
go get cloud.google.com/go/translate/apiv3
创建
app.go
文件。打开
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() { }
在
translateText()
函数中,添加以下代码,用于翻译指定文本。依次选择 File > Save 以重新设置代码格式: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
在
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) }
从终端运行您的应用。
go run app.go
Node.js
安装 Cloud Translation API Cloud 客户端库:
- 点击 Cloud Code,然后展开 Cloud API 资源管理器。
- 展开 Cloud AI,然后点击 Cloud Translation API。
- 如需安装客户端库,请点击 NodeJS,然后点击 play_arrow
在终端运行。
在项目中创建一个
app.js
文件。打开
app.js
,然后在文件开头导入 Translation 客户端库:const {TranslationServiceClient} = require('@google-cloud/translate');
创建一个 Translation API 客户端,并为您的项目 ID、位置和要翻译的文本添加变量:
// Instantiates a client const translationClient = new TranslationServiceClient(); const projectId = 'PROJECT_ID'; const location = 'global'; const text = 'Hello, world!';
添加以下
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}`); } }
在
app.js
文件末尾调用translateText()
:translateText();
如需运行应用,请打开命令面板(按
Ctrl
/Cmd
+Shift
+P
),然后运行 Cloud Code: Run on Kubernetes。部署应用后,请打开 webview 中显示的网址以查看正在运行的服务。
Python
安装 Cloud Translation API Cloud 客户端库:
- 点击 Cloud Code,然后展开 Cloud API 资源管理器。
- 展开 Cloud AI,然后点击 Cloud Translation API。
- 如需安装客户端库,请点击 Python,然后点击 play_arrow
在终端运行。
注意:如果您使用的是基于 Linux 的操作系统(包括 Chromebook),请将命令修改为使用pip3
而不是pip
。如果您使用的是 Mac,请修改命令以使用pip3
并添加--user
标志。
在项目中创建一个
app.py
文件。在
app.py
中,在文件开头导入客户端库:from google.cloud import translate
添加
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"
如需将文本从英语翻译成西班牙语并输出结果,请在
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))
在
app.py
末尾,调用translate_text()
。translate_text()
如需运行应用,请打开命令面板(按
Ctrl
/Cmd
+Shift
+P
),然后运行 Cloud Code: Run on Kubernetes。部署应用后,请打开 webview 中显示的网址以查看正在运行的服务。
清理
停止应用后,系统会自动删除在运行期间部署的所有 Kubernetes 资源。
为避免系统因本快速入门中使用的其他资源向您的帐号收取费用,如果您想重复使用该项目,请务必删除该项目或删除您创建的集群。
如需删除集群,请执行以下操作:
- 在 Kubernetes Explorer 中,暂停集群名称,然后点击 open_in_new 在 Google Cloud 控制台中打开。
- 点击删除,然后再次点击删除进行确认。
如需删除项目(以及关联的资源,包括所有集群),请执行以下操作:
- 在 Google Cloud 控制台中,进入管理资源页面。
- 在项目列表中,选择要删除的项目,然后点击删除。
- 在对话框中输入项目 ID,然后点击关闭以删除项目。
获取帮助
如需发送反馈,请在 GitHub 上报告问题,或者在 Stack Overflow 上提问。后续步骤
- 详细了解 Cloud Translation API
- 详细了解 Cloud 客户端库
- 详细了解 Cloud Code for VS Code