Cloud Code에서 Cloud 클라이언트 라이브러리 사용

이 페이지에서는 Cloud 클라이언트 라이브러리 및 Cloud Code를 빠르게 시작하는 방법을 설명합니다. Hello World 샘플 애플리케이션을 사용하여 새 Kubernetes 애플리케이션을 설정한 다음 Cloud Translation API를 사용하여 응답을 스페인어로 번역하도록 애플리케이션을 업데이트합니다.

시작하기 전에

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Google Kubernetes Engine and Cloud Translation 사용 설정

    API 사용 설정

  5. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  6. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  7. API Google Kubernetes Engine and Cloud Translation 사용 설정

    API 사용 설정

  8. Cloud Code가 샘플 클론과 같은 Git 작업을 수행할 수 있도록 Git를 설치합니다.
  9. 아직 설치하지 않은 경우 Cloud Code 플러그인을 설치합니다.

애플리케이션 만들기

  1. 명령어 팔레트(Cmd/Ctrl+Shift+P)에서 Cloud Code: New Application를 실행하고, Kubernetes 애플리케이션을 선택한 다음 원하는 언어로 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 사용자 역할을 부여합니다.

    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
    

Node.js

  1. Cloud Translation API Cloud 클라이언트 라이브러리를 설치합니다.

    1. Cloud Code를 클릭한 다음 Cloud APIs 탐색기를 펼칩니다.
    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. Hello, world! 텍스트의 언어를 감지하고 텍스트를 스페인어로 번역하는 다음 async 함수를 추가합니다.

    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: Kubernetes에서 실행를 실행합니다.

  8. 애플리케이션이 배포된 후에 webview에 표시된 URL을 열어 실행 중인 서비스를 확인합니다.

Python

  1. Cloud Translation API Cloud 클라이언트 라이브러리를 설치합니다.

    1. Cloud Code를 클릭한 다음 Cloud APIs 탐색기를 펼칩니다.
    2. Cloud AI를 펼친 후 Cloud Translation API를 클릭합니다.
    3. 클라이언트 라이브러리를 설치하려면 Python을 클릭한 다음 play_arrow 터미널에서 실행을 클릭합니다.
      참고: Chromebook을 포함한 Linux 기반 운영체제를 사용하는 경우 pip 대신 pip3를 사용하도록 명령어를 수정하세요. 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: Kubernetes에서 실행를 실행합니다.

  8. 애플리케이션이 배포된 후에 webview에 표시된 URL을 열어 실행 중인 서비스를 확인합니다.

삭제

애플리케이션을 중지하면 실행 중에 배포된 모든 Kubernetes 리소스가 자동으로 삭제됩니다.

이 빠른 시작에서 사용되는 다른 리소스에 대한 비용이 계정에 청구되지 않도록 하려면 프로젝트를 삭제하거나 프로젝트를 다시 사용하려면 만든 클러스터를 삭제해야 합니다.

클러스터를 삭제하려면 다음을 실행하세요.

  1. Kubernetes 탐색기에서 클러스터 이름을 일시중지한 후 open_in_new Google Cloud 콘솔에서 열기를 클릭합니다.
  2. 삭제를 클릭한 다음 삭제를 클릭합니다.

프로젝트 및 클러스터를 포함한 관련 리소스를 삭제하려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

지원 받기

의견을 보내려면 GitHub에서 문제를 보고하거나 Stack Overflow에서 질문하세요.

다음 단계