在 Cloud Code 中使用 Cloud 用戶端程式庫
本頁面說明如何快速開始使用 Cloud 用戶端程式庫和 Cloud Code。您將使用 Hello World 範例應用程式設定新的 Kubernetes 應用程式,然後更新應用程式,以便使用 Cloud Translation API 將回應翻譯成西班牙文。
事前準備
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Google Kubernetes Engine and Cloud Translation APIs.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Make sure that billing is enabled for your Google Cloud project.
-
Enable the Google Kubernetes Engine and Cloud Translation APIs.
- 安裝 Git,讓 Cloud Code 執行 Git 作業,例如複製範例。
- 如果尚未安裝 Cloud Code 外掛程式,請先安裝。
建立應用程式
- 在指令區塊面板 (
Cmd
/Ctrl
+Shift
+P
) 中,執行「Cloud Code:新應用程式」,然後選擇「Kubernetes 應用程式」,並選擇您偏好的語言的「Hello World」應用程式。舉例來說,您可以選擇「Node.js: Hello World」,建立 Node.js Hello World 應用程式啟動專案。 - 儲存新應用程式。系統會顯示通知,確認已建立應用程式,並開啟含有應用程式的新視窗。
設定憑證
如要開啟終端機,請依序點選「Terminal」>「New Terminal」。
建立服務帳戶來驗證 API 要求:
gcloud iam service-accounts create \ translation-quickstart \ --project PROJECT_ID
將 Cloud Translation API 使用者角色授予服務帳戶:
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 用戶端程式庫:
- 如要開啟終端機,請依序點選「Terminal」>「New Terminal」。
執行下列指令:
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
Java
開啟
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>
接著,在
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 支援的程式庫」。
系統詢問您是否要同步處理 Java 類別路徑/設定時,請按一下「Always」(一律)。
建立名為
app.java
的檔案。在
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;
將
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); }
新增過載的
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()); } } }
將
main
中的輸出陳述式替換為呼叫translateText()
:try { translateText(); } catch (IOException e) { e.printStackTrace(); }
Node.js
安裝 Cloud Translation API Cloud 用戶端程式庫:
- 按一下「Cloud Code」
,然後展開「Cloud APIs」Explorer。
- 展開「Cloud AI」,然後按一下「Cloud Translation API」。
- 如要安裝用戶端程式庫,請依序點選「NodeJS」和「Run in terminal」play_arrow。
- 按一下「Cloud Code」
在專案中建立
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 APIs」Explorer。
- 展開「Cloud AI」,然後按一下「Cloud Translation API」。
- 如要安裝用戶端程式庫,請依序點選「Python」和 play_arrow「在終端機中執行」。
注意:如果您使用的是 Chromebook 等以 Linux 為基礎的作業系統,請修改指令,改用pip3
而非pip
。如果您使用的是 Mac,請修改指令以使用pip3
,並新增--user
標記。
- 按一下「Cloud Code」
在專案中建立
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」open_in_new「Open in Google Cloud console」(在控制台中開啟)。
- 按一下「Delete」(刪除),然後點選「Delete」(刪除)。
如要刪除專案 (以及相關聯的資源,包括任何叢集),請按照下列步驟操作:
- In the Google Cloud console, go to the Manage resources page.
- In the project list, select the project that you want to delete, and then click Delete.
- In the dialog, type the project ID, and then click Shut down to delete the project.
取得支援
如要提供意見回饋,請在 GitHub 上回報問題,或在 Stack Overflow 上提問。後續步驟
- 進一步瞭解 Cloud Translation API
- 進一步瞭解 Cloud 用戶端程式庫
- 進一步瞭解 Cloud Code for VS Code