arrow_back

運用 Gemini Code Assist 建構應用程式

登录 加入
访问 700 多个实验和课程

運用 Gemini Code Assist 建構應用程式

实验 1 小时 30 分钟 universal_currency_alt 1 积分 show_chart 入门级
info 此实验可能会提供 AI 工具来支持您学习。
访问 700 多个实验和课程

總覽

在本實驗室中,您將使用 Google Cloud 的 AI 輔助應用程式開發工具 Gemini Code Assist 來測試、記錄及改良應用程式,也會請 Gemini 說明程式碼。

您會透過 Cloud Workstations 建立開發環境,以 Code OSS 做為整合式開發環境 (IDE)。

本實驗室適合各種經驗程度的應用程式開發人員,即使不熟悉如何開發雲端應用程式也能參加。

注意:Gemini 仍處於早期技術階段,因此可能會輸出看似合理卻與事實不符的內容。使用輸出內容前,請先確認內容是否屬實。如要瞭解詳情,請參閱 Gemini 版 Google Cloud 和負責任的 AI 技術

目標

在本實驗室,您將瞭解如何執行下列工作:

  • 使用 Cloud Workstations 建立雲端式應用程式開發環境。
  • 運用 Gemini Code Assist 說明程式碼。
  • 使用 Gemini Code Assist 生成單元測試。
  • 提示 Gemini 美化應用程式外觀。
  • 使用 Gemini Code Assist 讓程式碼更清楚易懂。
  • 透過 Gemini Code Assist 以英文或其他語言為程式碼加註。

設定

在每個研究室中,您都能在固定時間內免付費建立新的 Google Cloud 專案,並使用一組資源。

  1. 請透過無痕式視窗登入 Qwiklabs。

  2. 請記下研究室的存取時間 (例如 1:15:00),並確保自己能在時間限制內完成作業。
    研究室不提供暫停功能。如有需要,您可以重新開始,但原先的進度恕無法保留。

  3. 準備就緒後,請按一下「Start lab」

  4. 請記下研究室憑證 (使用者名稱密碼),這組資訊將用於登入 Google Cloud 控制台。

  5. 按一下「Open Google Console」

  6. 按一下「Use another account」,然後複製這個研究室的憑證,並貼入提示訊息。
    如果使用其他憑證,系統會顯示錯誤或向您收取費用

  7. 接受條款,然後略過資源復原頁面。

啟用 Cloud Shell

Cloud Shell 是含有多項開發工具的虛擬機器,提供永久的 5 GB 主目錄,並在 Google Cloud 中運作。Cloud Shell 可讓您透過指令列存取 Google Cloud 資源。gcloud 是 Google Cloud 的指令列工具,已預先安裝於 Cloud Shell,並支援 Tab 鍵完成功能。

  1. 在控制台的右上方,點按「啟用 Cloud Shell」按鈕

  2. 點按「繼續」
    請稍候片刻,等待系統完成佈建作業並連線至環境。連線建立後,即代表您已通過驗證,且專案已設為「PROJECT_ID」

指令範例

  • 列出目前使用的帳戶名稱:
gcloud auth list

輸出內容

Credentialed accounts: - <myaccount>@<mydomain>.com (active)

輸出內容範例

Credentialed accounts: - google1623327_student@qwiklabs.net
  • 列出專案 ID:
gcloud config list project

輸出內容

[core] project = <project_ID>

輸出內容範例

[core] project = qwiklabs-gcp-44776a13dea667a6 注意:如需 gcloud 的完整說明,請參閱 gcloud CLI 總覽指南

工作 1:設定環境和帳戶

在這項工作中,您將啟用 Gemini 的 Cloud AI Companion API,並為使用者帳戶授予必要的角色。

設定 API 和角色

  1. 使用實驗室憑證登入 Google Cloud 控制台,然後依序按下鍵盤的 GS 鍵,開啟 Cloud Shell 終端機。

  2. 執行下列指令,在 Cloud Shell 設定專案 ID、使用者和區域環境變數:

    export PROJECT_ID=$(gcloud config list project --format="value(core.project)") export USER=$(gcloud config list account --format "value(core.account)") export REGION={{{project_0.startup_script.lab_region| Lab Region}}} echo "PROJECT_ID=${PROJECT_ID}" echo "USER=${USER}" echo "REGION=${REGION}"
  3. 執行下列指令,啟用 Gemini 的 Cloud AI Companion API,並為使用者帳戶授予必要的角色:

    gcloud services enable cloudaicompanion.googleapis.com --project ${PROJECT_ID} gcloud projects add-iam-policy-binding ${PROJECT_ID} --member user:${USER} --role=roles/cloudaicompanion.user gcloud projects add-iam-policy-binding ${PROJECT_ID} --member user:${USER} --role=roles/serviceusage.serviceUsageViewer

點選「Check my progress」,確認目標已達成。 啟用相關 API 並設定 IAM 角色

工作 2:建立 Cloud Workstations 工作站

本實驗室透過 Cloud Workstations IDE 的 Cloud Code 外掛程式,在 Gemini 的協助下開發應用程式。Cloud Workstations 是全代管的整合式開發環境,與 Gemini 原生整合。

在這項工作中,您將設定及佈建 Cloud Workstations 環境,然後啟用 Cloud Code 外掛程式,以便使用 Gemini。

查看工作站叢集

本實驗室已預先建立名為 my-cluster 的工作站叢集,用於設定及建立工作站。

  1. 前往 Google Cloud 控制台,在標題列的「搜尋」欄位輸入 Cloud Workstations,然後點選「Cloud Workstations」,開啟「工作站」頁面。

  2. 如果「Cloud Workstations」未固定 (),請在「導覽選單」 點選「固定」圖示

  3. 導覽窗格,點選「管理叢集」

  4. 檢查叢集的狀態。如果叢集狀態為 ReconcilingUpdating,請隔一段時間再重新整理,待狀態變為 Ready 後,即可進行下一個步驟。

建立設定和工作站

  1. 在 Cloud Shell 執行下列指令,建立工作站設定和工作站:

    export CLUSTER_NAME=my-cluster export CONFIG_NAME=my-config export WS_NAME=my-workstation export REGION={{{project_0.startup_script.lab_region| Lab Region}}} gcloud workstations configs create ${CONFIG_NAME} --cluster=${CLUSTER_NAME} --region=${REGION} --machine-type="e2-standard-4" --pd-disk-size=200 --pd-disk-type="pd-standard" --pool-size=1 gcloud workstations create ${WS_NAME} --cluster=${CLUSTER_NAME} --config=${CONFIG_NAME} --region=${REGION}

    等待指令執行完畢。

  2. 導覽窗格,點選「工作站」

    工作站建立後會列在「我的工作站」下方,並顯示 Stopped 狀態。

  3. 點選「啟動」,即可啟動工作站

    工作站啟動後,狀態會變更為 Starting。待狀態變為 Running 時,即表示工作站可以使用。

啟動 IDE

瀏覽器需要允許第三方 Cookie,部分擴充功能才能正常運作。

  1. 現在要在 Chrome 允許第三方 Cookie。請點按 Chrome 選單中的「設定」。

  2. 在搜尋列輸入「第三方 Cookie」。

  3. 點按「第三方 Cookie」設定,然後選取「允許第三方 Cookie」。

    注意:如要在完成實驗室後還原瀏覽器目前的設定,請記下原本的第三方 Cookie 設定。
  4. 在 Google Cloud 控制台的「工作站」頁面點選「啟動」,即可啟動工作站的 Code OSS IDE。

    IDE 會在新的瀏覽器分頁中開啟。

點選「Check my progress」,確認目標已達成。 建立並啟動 Cloud Workstations 工作站

工作 3:更新 Cloud Code 擴充功能並啟用 Gemini

在這項工作中,您將為工作站 IDE 啟用 Gemini in Cloud Code。

連線至 Google Cloud

請按照下列步驟,在工作站連線至 Google Cloud:

  1. 點選視窗底部狀態列的「Cloud Code - Sign In」,然後開啟瀏覽器中終端機顯示的連結,啟動「Cloud Code - Sign In」流程。

  2. 如果系統向您確認是否要開啟外部網站,請點選「開啟」

  3. 選擇帳戶 ,之後便會繼續前往 Gemini Code Assist。接著請點選「登入」

    瀏覽器分頁會顯示驗證碼。

    注意:系統可能會發出警示,顯示您已執行 gcloud auth login 指令。這是正常程序。IDE 已為您執行這項指令。
  4. 點選「複製」

  5. 返回 IDE,在終端機顯示 Enter authorization code 的位置貼上驗證碼。

  6. 如果系統要求您允許從剪貼簿複製,請點選「允許」

  7. 按下 Enter 鍵,然後等候狀態列顯示「Cloud Code - No Project」

    您已連線到 Google Cloud。

啟用 Gemini in Cloud Code

請按照以下步驟,為工作站 IDE 啟用 Gemini in Cloud Code:

  1. 點選工作站 IDE 中的選單圖示 ,然後依序前往「File」>「Preferences」>「Settings」

  2. 在「Search settings」中輸入 Gemini

  3. 在「Settings」對話方塊的「User」分頁中,依序選取「Extensions」>「Gemini Code Assist」

  4. 在 Cloud Code 設定頁面中的「Geminicodeassist: Project」部分,輸入 Google Cloud 專案 ID

  5. 點選視窗底部狀態列中的「Cloud Code - No Project」,選取 Cloud Code 的專案,然後依序選取「Select a Google Cloud project」選項和

    專案 ID 已顯示在狀態列中。現在可以使用 Gemini 了。

工作 4:下載、檢查及執行 Python Flask 應用程式

Python Flask 應用程式的程式碼已儲存至 Cloud Storage bucket。

在這項工作中,您將在 IDE 下載、檢查及執行 Python Flask 應用程式。Gemini Code Assist 會說明程式碼。

登入終端機。

  1. 在 IDE 選單 中,依序選取「Terminal」>「New Terminal」

  2. 在終端機執行下列指令:

    gcloud auth login

    開啟瀏覽器中終端機顯示的連結。

  3. 選擇帳戶 ,接下來會顯示「登入 Google Cloud SDK」的畫面,請點選「繼續」

  4. 最後,在「『Google Cloud SDK』想要存取您的 Google 帳戶」視窗中,點選「允許」

    瀏覽器分頁會顯示驗證碼。

    注意:系統可能會發出警示,顯示您已執行 gcloud auth login 指令。這是正常程序。IDE 已為您執行這項指令。
  5. 點選「複製」

  6. 返回 IDE,在終端機顯示 Enter the verification code provided in your browser 的位置貼上驗證碼,然後按下 Enter 鍵。

    終端機工作階段已登入 Google Cloud。

安裝 Python 虛擬環境

  1. 執行下列指令,在本機虛擬環境中安裝 Python:

    sudo apt update sudo apt -y upgrade sudo apt install -y python3-venv python3 -m venv ~/env source ~/env/bin/activate
  2. 執行下列指令,查看要使用的 Python 位置:

    which python3

複製程式碼

  1. 在終端機執行下列指令,複製應用程式程式碼:

    export PROJECT_ID={{{project_0.project_id | Project ID}}} export BUCKET_NAME=$PROJECT_ID-code gcloud storage cp -r gs://$BUCKET_NAME/* .

    程式碼已複製到 codeassist-demo 子目錄。

  2. 在 IDE 活動列,依序點選「Explorer」圖示 和「Open Folder」

  3. 在「Open Folder」對話方塊,依序點選「codeassist-demo」和「OK」

    系統便會顯示目錄結構。

檢查程式碼

  1. 選取「main.py」

    這個 Python 檔案會在編輯器視窗中開啟。

  2. 在 IDE 活動列點選「Gemini Code Assist」圖示

    Gemini Code Assist 是一個 AI 輔助開發工具,可協助您完成應用程式開發工作。

  3. Gemini Code Assist 對話窗格,輸入下列提示詞並點選「Send」圖示

    Explain this

    提示詞是指透過問題或陳述來說明您需要什麼樣的協助。提示詞中可加入現有程式碼的背景資訊。Google Cloud 會分析這些資訊,提供更實用或完整的回覆。對於如何撰寫提示詞才能生成好的回覆,請參閱這篇文章,進一步瞭解撰寫優質 Gemini for Google Cloud 提示詞的做法。

    Gemini 會說明 main.py 中的程式碼,回覆中可能會包含下列部分的說明:

    • 依附元件
    • 應用程式設定
    • 路由
    • 應用程式的執行方式

    使用這組提示詞時,如果選取特定程式碼區塊,Gemini Code Assist 只會說明選取的部分。

    注意:對話記錄狀態只會保存在記憶體中,轉換至其他工作區或關閉 IDE 後,系統並不會保留這類資料。我們不會將您的提示詞或產生的回覆內容做為 Gemini 模型的訓練資料。詳情請參閱「Gemini for Google Cloud 如何使用您的資料」。
  4. 在編輯器中選取 app.routePOST /convert 路由的函式定義,然後依序點選燈泡圖示 和「Gemini: Explain this」

    Gemini 會詳細說明所選程式碼。

執行應用程式

  1. 如果終端機已關閉,請在 IDE 選單 中依序選取「Terminal」>「New Terminal」

  2. 在終端機執行下列指令:

    cd ~/codeassist-demo source ~/env/bin/activate python3 main.py

    指令會傳回錯誤訊息,表示沒有 flask 模組。Gemini Code Assist 可協助您瞭解問題。

  3. Gemini Code Assist 對話窗格,輸入下列提示詞:

    How do you install Python requirements?

    Gemini Code Assist 可能會提到可使用 pip 套件安裝程式和 requirements.txt 檔案安裝 Python 所需的項目。

  4. 在 IDE 活動列,依序點選「Explorer」圖示 和「requirements.txt」

    Flask 和所需版本都列在 requirements.txt 檔案中。

  5. 在終端機執行下列指令:

    pip install -r requirements.txt

    Flask 已完成安裝。

  6. 在終端機執行下列指令:

    python3 main.py

    系統會顯示對話方塊,指出監聽通訊埠 8080 的服務已可透過網頁預覽。

  7. 依序點選「Open Preview」和「Open」

    Roman Numerals 網頁應用程式會在新的分頁中開啟。

  8. 在數字方塊中輸入 123,然後點選「Convert」

    傳回的數字是 CXXIIIC 為 100,X 是 10,I 則是 1。看起來正確無誤。

  9. 點選「Return to home page」,輸入 45,然後點選「Convert」

    傳回的數字是 XXXXV。從數學角度來看,這是正確的 (4 個 10,再加 5),但 40 通常會以 XL (50 減 10) 表示,因此更傳統的羅馬數字寫法應該是 XLV

    這部分稍後會再進一步說明。

  10. 在 IDE 活動列,依序點選「Explorer」圖示 和「calendar.py」

    number_to_roman 函式會將數字轉換為羅馬數字。

點選「Check my progress」,確認目標已達成。 複製程式碼並執行 Python Flask 應用程式

工作 5:新增單元測試

在這項工作中,您會使用 Gemini Code Assist 生成程式碼的單元測試。

  1. 在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:

    Create unit tests for a fixed version of number_to_roman

    目前開啟的分頁是 calendar.pyGemini Code Assist 會辨識這個分頁中的程式碼,且應該會提供範例程式碼,大致如下:

    import unittest import calendar class TestNumberToRoman(unittest.TestCase): def test_basic_conversions(self): self.assertEqual(calendar.number_to_roman(1), "I") self.assertEqual(calendar.number_to_roman(5), "V") self.assertEqual(calendar.number_to_roman(10), "X") self.assertEqual(calendar.number_to_roman(50), "L") self.assertEqual(calendar.number_to_roman(100), "C") self.assertEqual(calendar.number_to_roman(500), "D") self.assertEqual(calendar.number_to_roman(1000), "M") def test_combinations(self): self.assertEqual(calendar.number_to_roman(4), "IV") self.assertEqual(calendar.number_to_roman(9), "IX") self.assertEqual(calendar.number_to_roman(14), "XIV") self.assertEqual(calendar.number_to_roman(40), "XL") self.assertEqual(calendar.number_to_roman(90), "XC") self.assertEqual(calendar.number_to_roman(400), "CD") self.assertEqual(calendar.number_to_roman(900), "CM") self.assertEqual(calendar.number_to_roman(1994), "MCMXCIV") self.assertEqual(calendar.number_to_roman(3888), "MMMDCCCLXXXVIII") def test_edge_cases(self): self.assertEqual(calendar.number_to_roman(0), "") # Should handle zero self.assertRaises(TypeError, calendar.number_to_roman, "abc") # Should handle invalid input def test_large_numbers(self): self.assertEqual(calendar.number_to_roman(3000), "MMM") self.assertEqual(calendar.number_to_roman(3999), "MMMCMXCIX") if __name__ == '__main__': unittest.main() 注意:Gemini 可能會以目前實作的程式碼為基準,建立會通過的單元測試,而非根據標準羅馬數字表示規則來建立測試。在本實驗室中,您將使用正確版本的單元測試。
  2. 在終端機按下 CTRL + C 鍵,讓執行中的應用程式停止執行。

  3. 在終端機執行下列指令,建立轉換函式的單元測試:

    cat > ~/codeassist-demo/test_calendar.py <<EOF import unittest import calendar class TestNumberToRoman(unittest.TestCase): def test_basic_conversions(self): self.assertEqual(calendar.number_to_roman(1), "I") self.assertEqual(calendar.number_to_roman(5), "V") self.assertEqual(calendar.number_to_roman(10), "X") self.assertEqual(calendar.number_to_roman(50), "L") self.assertEqual(calendar.number_to_roman(100), "C") self.assertEqual(calendar.number_to_roman(500), "D") self.assertEqual(calendar.number_to_roman(1000), "M") def test_combinations(self): self.assertEqual(calendar.number_to_roman(4), "IV") self.assertEqual(calendar.number_to_roman(9), "IX") self.assertEqual(calendar.number_to_roman(14), "XIV") self.assertEqual(calendar.number_to_roman(40), "XL") self.assertEqual(calendar.number_to_roman(90), "XC") self.assertEqual(calendar.number_to_roman(400), "CD") self.assertEqual(calendar.number_to_roman(900), "CM") self.assertEqual(calendar.number_to_roman(1994), "MCMXCIV") self.assertEqual(calendar.number_to_roman(3888), "MMMDCCCLXXXVIII") def test_edge_cases(self): self.assertEqual(calendar.number_to_roman(0), "") # Should handle zero self.assertRaises(TypeError, calendar.number_to_roman, "abc") # Should handle invalid input def test_large_numbers(self): self.assertEqual(calendar.number_to_roman(3000), "MMM") self.assertEqual(calendar.number_to_roman(3999), "MMMCMXCIX") if __name__ == '__main__': unittest.main() EOF
  4. 在終端機執行下列指令來執行測試:

    cd ~/codeassist-demo python3 test_calendar.py

    測試會失敗:

    ====================================================================== ERROR: test_edge_cases (__main__.TestNumberToRoman.test_edge_cases) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/codeassist-demo/test_calendar.py", line 28, in test_edge_cases self.assertRaises(TypeError, calendar.number_to_roman, "abc") # Should handle invalid input ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/unittest/case.py", line 778, in assertRaises return context.handle('assertRaises', args, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/unittest/case.py", line 238, in handle callable_obj(*args, **kwargs) File "/home/user/codeassist-demo/calendar.py", line 16, in number_to_roman number = int(number) ^^^^^^^^^^^ ValueError: invalid literal for int() with base 10: 'abc' ====================================================================== FAIL: test_combinations (__main__.TestNumberToRoman.test_combinations) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/codeassist-demo/test_calendar.py", line 16, in test_combinations self.assertEqual(calendar.number_to_roman(4), "IV") AssertionError: 'IIII' != 'IV' - IIII + IV ====================================================================== FAIL: test_large_numbers (__main__.TestNumberToRoman.test_large_numbers) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/user/codeassist-demo/test_calendar.py", line 33, in test_large_numbers self.assertEqual(calendar.number_to_roman(3999), "MMMCMXCIX") AssertionError: 'MMMDCCCCLXXXXVIIII' != 'MMMCMXCIX' - MMMDCCCCLXXXXVIIII + MMMCMXCIX ---------------------------------------------------------------------- Ran 4 tests in 0.004s FAILED (failures=2, errors=1)

    失敗的部分如下:

    • abc 未正確處理。
    • 輸入 4 後,傳回的是 IIII,而非 IV
    • 輸入 3999 後,傳回的是 MMMDCCCCLXXXXVIIII,而非 MMMCMXCIX

    在每個測試函式中,只要遇到第一個錯誤,函式就會停止執行。

    注意:如果用來測試的程式碼不同,結果可能會有所差異。

點選「Check my progress」,確認目標已達成。 建立轉換函式的單元測試

工作 6:讓程式碼更清楚易懂,並修正錯誤

在這項工作中,您會透過 Gemini Code Assist 使程式碼更清楚易懂,並修正其中的錯誤。

  1. 在 IDE 活動列,依序點選「Explorer」圖示 和「calendar.py」

  2. 在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:

    Make my code more readable and fix any errors

    Gemini Code Assist 會提供更清楚易懂的程式碼,且可能會修正其中的錯誤。範例如下:

    def number_to_roman(number): """Converts an integer to its Roman numeral equivalent. Args: number: An integer between 0 and 3999. Returns: A string representing the Roman numeral equivalent of the number. Returns an empty string if the input is 0. Raises TypeError if the input is not an integer or is out of range. """ try: number = int(number) except ValueError: raise TypeError("Input must be an integer.") if not 0 <= number <= 3999: raise TypeError("Input must be between 0 and 3999.") if number == 0: return "" roman_map = { 1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'} result = "" for value, numeral in roman_map.items(): while number >= value: result += numeral number -= value return result

    Gemini Code Assist 也會說明所做的變更:

    Key improvements: 1. Error Handling: Added TypeError for non-integer input and values outside the range 0-3999. This makes the function more robust. 2. Docstring: A clear docstring explains the function's purpose, arguments, return value, and error handling. This significantly improves readability and maintainability. 3. Efficiency and Correctness: Uses a roman_map dictionary and a more efficient algorithm to construct the Roman numeral. This handles subtractive notation (like "IV" for 4, "IX" for 9, etc.) correctly. The previous version had issues with these cases and was less efficient. 4. Zero Handling: Explicitly handles the case where the input number is 0, returning an empty string as expected. 5. Clarity: The code is now more concise and easier to understand. The logic is clearer and the variable names are more descriptive. This revised version addresses the limitations and errors of the original implementation and adheres to best practices for Python code. It's more robust, readable, and efficient.

    在這個範例中,Gemini Code Assist 提供的演算法不僅讓程式碼更清楚易懂,也修正了其中的問題。

  3. Gemini Code Assist 的程式碼窗格,點選「Diff with Open File」圖示 ,在新檔案比較程式碼。

  4. 點選「Accept」,接受變更。系統就會接受更新版程式碼。

  5. 在終端機執行下列指令:

    cd ~/codeassist-demo python3 test_calendar.py

    如未通過測試,請試著執行幾次,確保測試使用的不是快取版本的日曆模組。

    如果 Gemini 未修正羅馬數字問題,部分測試就會失敗。如果發生這種情況,您可以自行修正程式碼,直到通過測試為止,或是將 calendar.py 替換成已知可正常運作的版本。

  6. 如果部分測試失敗,請執行下列指令來修正程式碼並重新執行單元測試:

    cat > ~/codeassist-demo/calendar.py <<EOF def number_to_roman(number): """Converts an integer to its Roman numeral equivalent. Args: number: An integer between 0 and 3999. Returns: A string representing the Roman numeral equivalent of the number. Returns an empty string if the input is 0. Raises TypeError if the input is not an integer or is out of range. """ try: number = int(number) except ValueError: raise TypeError("Input must be an integer.") if not 0 <= number <= 3999: raise TypeError("Input must be between 0 and 3999.") if number == 0: return "" roman_map = { 1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40: 'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'} result = "" for value, numeral in roman_map.items(): while number >= value: result += numeral number -= value return result EOF cd ~/codeassist-demo python3 test_calendar.py

    現在應該會通過測試。

點選「Check my progress」,確認目標已達成。 更新 calendar.py,修正程式碼問題

工作 7:協助非英文母語者理解程式碼

如果您的母語不是英文,需要使用翻譯應用程式,可以使用 Gemini Code Assist 生成其他語言的註解。

在這項工作中,您會使用 Gemini Code Assist 為程式碼加註,並加入另一種語言的註解。

  1. 在 IDE 活動列,依序點選「Explorer」圖示 和「main.py」

  2. 在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:

    Add comments to main.py

    Gemini Code Assist 會加入註解來說明程式碼:

    import os # Import the os module for environment variables from flask import Flask, render_template, request # Import Flask framework components import calendar # Import the calendar module for Roman numeral conversion # Create a Flask app instance app = Flask(__name__) # Define a route for the home page @app.route("/", methods=["GET"]) def home_page(): # Render the index.html template return render_template("index.html") # Define a route for the conversion endpoint @app.route("/convert", methods=["POST"]) def convert(): # Get the number from the form data number = request.form["number"] # Convert the number to Roman numerals using the calendar module roman = calendar.number_to_roman(number) # Render the convert.html template with the number and its Roman numeral equivalent return render_template("convert.html", number=number, roman=roman) # Run the Flask app if this script is executed directly if __name__ == "__main__": # Run the app in debug mode, listening on all interfaces (0.0.0.0) # and using the port specified in the environment variable PORT or defaulting to 8080 app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

    但如果英文不是您的母語呢?

  3. Gemini Code Assist 窗格輸入下列提示詞:

    Add Spanish comments to main.py

    Gemini Code Assist 可提供不同語言的註解,協助使用者理解程式碼。

  4. Gemini Code Assist 的程式碼窗格,點選「Diff with Open File」圖示 ,確認只加入註解。

    系統會顯示更新內容與現有程式碼的比較畫面:

  5. 點選「Decline」,拒絕變更。

工作 8:美化應用程式外觀

Gemini Code Assist 還能協助您打造更美觀的應用程式。

在這項工作中,您會使用 Gemini Code Assist 改良應用程式的視覺設計。

  1. 在終端機執行下列指令:

    cd ~/codeassist-demo python3 main.py

    系統會顯示對話方塊,指出監聽通訊埠 8080 的服務已可透過網頁預覽。

  2. 依序點選「Open Preview」和「Open」

    Roman Numerals 網頁應用程式會在新的分頁中開啟。

  3. 在 IDE 活動列,依序點選「Explorer」圖示 和「templates/index.html」

    這個應用程式的 HTML 範本非常簡單。

  4. 在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:

    Make this HTML template look better

    Gemini Code Assist 會更新程式碼,美化應用程式進入頁面的外觀。

  5. 在 Gemini Code Assist 的程式碼窗格,依序點選「Diff with Open File」圖示 和「Accept」來接受變更。

  6. 返回 Roman Numerals 應用程式瀏覽器分頁,然後點選「重新整理」

    應用程式應該變得更好看了。在本例中,對話方塊移到頁面中間,並加上了顏色。

    注意:Gemini Code Assist 幫您做的調整可能會有所不同。
  7. 在 IDE 活動列,依序點選「Explorer」圖示 和「templates/convert.html」

  8. 在 IDE 活動列點選「Gemini Code Assist」圖示 ,然後輸入下列提示詞:

    Make the convert.html template look similar to the index.html template

    Gemini Code Assist 會根據索引範本更新結果範本,確保兩者一致。

  9. 在 Gemini Code Assist 的程式碼窗格,依序點選「Diff with Open File」圖示 和「Accept」來接受變更。

  10. 返回 Roman Numerals 應用程式瀏覽器分頁,輸入 45 後再按下 Enter 鍵。

    新的結果頁面風格應該會與索引頁面一致:

點選「Check my progress」,確認目標已達成。 使用 Gemini Code Assist 改良應用程式的視覺設計

關閉研究室

如果您已完成研究室,請按一下「End Lab」(關閉研究室)。Qwiklabs 會移除您已用的資源,並清除使用帳戶。

您可以為研究室的使用體驗評分。請選取合適的星級評等並提供意見,然後按一下「Submit」(提交)

星級評等代表您的滿意程度:

  • 1 星 = 非常不滿意
  • 2 星 = 不滿意
  • 3 星 = 普通
  • 4 星 = 滿意
  • 5 星 = 非常滿意

如果不想提供意見回饋,您可以直接關閉對話方塊。

如有任何想法、建議或指教,請透過「Support」(支援) 分頁提交。

恭喜!

在本實驗室中,您已學會如何:

  • 使用 Cloud Workstations 建立雲端式應用程式開發環境。
  • 運用 Gemini Code Assist 說明程式碼。
  • 使用 Gemini Code Assist 生成單元測試。
  • 提示 Gemini 美化應用程式外觀。
  • 使用 Gemini Code Assist 讓程式碼更清楚易懂。
  • 透過 Gemini Code Assist 以英文或其他語言為程式碼加註。

後續行動/瞭解詳情

Copyright 2024 Google LLC 保留所有權利。Google 和 Google 標誌是 Google LLC 的商標,其他公司和產品名稱則有可能是其關聯公司的商標。

准备工作

  1. 实验会创建一个 Google Cloud 项目和一些资源,供您使用限定的一段时间
  2. 实验有时间限制,并且没有暂停功能。如果您中途结束实验,则必须重新开始。
  3. 在屏幕左上角,点击开始实验即可开始

此内容目前不可用

一旦可用,我们会通过电子邮件告知您

太好了!

一旦可用,我们会通过电子邮件告知您

一次一个实验

确认结束所有现有实验并开始此实验

使用无痕浏览模式运行实验

请使用无痕模式或无痕式浏览器窗口运行此实验。这可以避免您的个人账号与学生账号之间发生冲突,这种冲突可能导致您的个人账号产生额外费用。