1. 簡介
上次更新時間:2021 年 5 月 11 日
什麼是 Cloud SQL?
Cloud SQL 是一項全代管資料庫服務,能讓您輕鬆設定、維護、管理及操作 Google Cloud Platform 上的關聯式資料庫。
什麼是 Cloud Functions?
Cloud Functions 是一項簡易運算解決方案,可讓開發人員建立獨立的單一用途函式來回應雲端事件,而不需要管理伺服器或執行階段環境。
建構項目
在本程式碼研究室中,您將以 Python 編寫 Cloud Function。函式:
- 連線至 Cloud SQL 資料庫執行個體。
- 將插入陳述式傳送至資料庫中的資料表。
課程內容
- 如何在 Google Cloud 控制台中存取 Cloud Functions 網頁版 UI。
- 如何建立 Cloud 函式。
- 如何測試 Cloud Function。
- 如何使用 Python 連線至 Cloud SQL 資料庫執行個體 (MySQL 或 PostgreSQL)。
- 如何使用 Python 寫入 Cloud SQL 資料庫。
2. 需求條件
- 瀏覽器,例如 Chrome 或 Firefox。
- 包含 Cloud SQL 執行個體的 Google Cloud Platform 專案。
- 如果沒有,請按照 MySQL 或 PostgreSQL 快速入門導覽課程中的步驟操作。完成所有步驟,但不要執行清除作業。
- 執行個體包含具有資料表的 MySQL 或 PostgreSQL 資料庫。
- 執行個體連線名稱、資料庫和資料表名稱、資料庫使用者名稱和使用者密碼。
- 具備「Cloud SQL 用戶端」角色的服務帳戶。
3. 準備程式碼並建立函式
準備程式碼
您可以在這裡找到連線至 Cloud SQL 資料庫的 Cloud Functions 程式碼。部分變數值取決於 Cloud SQL 資料庫是 MySQL 還是 PostgreSQL,以及您自己的資料庫資訊。
Cloud 控制台中的 Cloud Functions UI 包含文字編輯器。您可以在該處複製/貼上並編輯程式碼,也可以先在本機編輯程式碼,然後複製/貼上到 UI 中。
requirements.txt
# This file tells Python which modules it needs to import
SQLAlchemy==1.3.12
# If your database is MySQL, uncomment the following line:
#PyMySQL==0.9.3
# If your database is PostgreSQL, uncomment the following line:
#pg8000==1.13.2
main.py
# This file contains all the code used in the codelab.
import sqlalchemy
# Depending on which database you are using, you'll set some variables differently.
# In this code we are inserting only one field with one value.
# Feel free to change the insert statement as needed for your own table's requirements.
# Uncomment and set the following variables depending on your specific instance and database:
#connection_name = ""
#table_name = ""
#table_field = ""
#table_field_value = ""
#db_name = ""
#db_user = ""
#db_password = ""
# If your database is MySQL, uncomment the following two lines:
#driver_name = 'mysql+pymysql'
#query_string = dict({"unix_socket": "/cloudsql/{}".format(connection_name)})
# If your database is PostgreSQL, uncomment the following two lines:
#driver_name = 'postgres+pg8000'
#query_string = dict({"unix_sock": "/cloudsql/{}/.s.PGSQL.5432".format(connection_name)})
# If the type of your table_field value is a string, surround it with double quotes.
def insert(request):
request_json = request.get_json()
stmt = sqlalchemy.text('insert into {} ({}) values ({})'.format(table_name, table_field, table_field_value))
db = sqlalchemy.create_engine(
sqlalchemy.engine.url.URL(
drivername=driver_name,
username=db_user,
password=db_password,
database=db_name,
query=query_string,
),
pool_size=5,
max_overflow=2,
pool_timeout=30,
pool_recycle=1800
)
try:
with db.connect() as conn:
conn.execute(stmt)
except Exception as e:
return 'Error: {}'.format(str(e))
return 'ok'
建立函式
- 在瀏覽器中前往 Google Cloud Platform Console 使用者介面。
- 從導覽選單中選取「Cloud Functions」。
- 按一下按鈕列中的「建立函式」。
- 輸入函式名稱。
- 選取「HTTP」HTTP觸發條件。(請記下觸發條件項目下方顯示的網址。格式如下:https://REGION-PROJECT_ID.cloudfunctions.net/FUNCTION_NAME
- 在「Authentication」(驗證) 下方,選取「Allow unauthenticated invocations」(允許未經驗證的叫用),即可公開發布函式。
- 展開「執行階段、建構作業和連線設定」。在「執行階段服務帳戶」中,選取具有「Cloud SQL 用戶端」角色的服務帳戶。
- 按一下「下一步」按鈕。
- 為「執行階段」選項選取「Python 3.7」。
- 選取「原始碼」選項的「內嵌編輯器」。
- 在來源程式碼編輯器視窗中,刪除 requirements.txt 和 main.py 的現有內容,並替換為上述程式碼的編輯版本。
- 輸入「insert」做為進入點的名稱。
- 按一下「部署」,然後等待函式建立完成。函式準備就緒時,旋轉圖示會停止旋轉,後續頁面會顯示綠色勾號。
4. 測試函式
- 在瀏覽器中前往 Google Cloud Platform Console 使用者介面。
- 從導覽選單中選取「Cloud Functions」。
- 按一下您先前建立的函式名稱。
- 選取頁面中間的「測試」連結。
- 選取「測試函式」。
- 結果應會顯示「ok」 (如果測試失敗,您會看到堆疊追蹤記錄,有助於偵錯)。
- 在瀏覽器中前往您先前建立函式時儲存的網址。如果忘記儲存網址,可以從「觸發條件」連結取得。
- 瀏覽器中也會顯示 ok 結果。
5. 清除所用資源
如要避免系統向您的 Google Cloud 帳戶收取本程式碼研究室所用資源的費用,請按照下列步驟操作。
刪除 Cloud SQL 執行個體
- 前往 Google Cloud 控制台的 Cloud SQL 執行個體頁面。
- 選取您建立的執行個體,開啟「執行個體詳細資料」頁面。
- 在頁面頂端的圖示列中,按一下 [刪除]。
- 在「Delete instance」(刪除執行個體) 視窗中輸入執行個體名稱,然後按一下「Delete」(刪除) 刪除執行個體。執行個體刪除後,您大約在 7 天內無法重複使用該執行個體名稱。
刪除 Cloud 函式
- 前往 Google Cloud 控制台的 Cloud Functions 頁面。
- 選取函式「動作」下方的三點圖示,然後選擇「刪除」。
- 按一下「刪除」按鈕,確認要刪除。
6. 恭喜
恭喜!您已成功建構可搭配 Cloud SQL 使用的 Cloud Function。
具體來說,您已建立 Cloud Function,可連線至 Cloud SQL 資料庫執行個體並寫入資料。