Try   HackMD

Lecture 5 - Cloud Function的入門與部署(Python)

tags: GCP Firestore Cloud Function Python


一、什麼是Cloud Function?

Google Cloud Functions 是一個可以建置並連結多個雲端服務的無伺服器執行環境。透過 Cloud Functions,您可以將那些簡單且單一的功能附加在從您雲端基礎設施/服務送出的 events 上。當 event 發生的時候,Cloud Functions 會被啟動,您的程式碼將被執行在一個完全代管的環境下,您不必額外設定基礎設施或是擔心要管理伺服器了。

Google Cloud Functions可以用Node.js, Python和Go編寫,並在特定於語言的運行時中執行。Cloud Functions執行環境也會因為選擇的運行時而產生差異。此處將使用Python來做Cloud Function的部署與建置。


二、工具需求

本文主要是先建置Firebase的開發環境,需要安裝的工具為:

  • Python(事先安裝)
  • Sublime/VS Code/Pycharm等任何可用來編譯Python的程式編輯器(事先安裝)
  • Google Cloud SDK(本文詳述)
  • pip install flask(本文詳述)
  • 依附元件(本文詳述)
Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
資料來源:https://blog.gcp.expert/cloud-functions-introduction/

三、入門與部署

方法一:直接使用Firestore的圖形化介面

點擊側邊欄的Function進入介面,官方就會提供教學流程給大家。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

不過這個方法筆者個人在使用的時候發現佈署常常會失敗,而原因是官方提供的教學流程不夠詳細,常常會有很多漏打的指定而需要debug,因此會建議第一次要使用的話直接採用 下方方法二 或是 使用node.js進行佈署 尤佳。

方法二:使用 gcloud指令部署

第一步:下載Google Cloud SDK(因為要使用gcloud)

  • 可直接參考網址,執行至「初始化 SDK」結束即可
  • 在初始化與驗證成功後,瀏覽器會顯示如下圖:
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
小提醒:不管是使用GCP平台上的甚麼工具,都需要事先做這個步驟(包刮App Engine、Cloud Function等。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
參考資料:https://cloud.google.com/sdk/docs/quickstart-windows

第二步:編寫Cloud Function

Cloud Function有兩種不同類型:HTTP功能和後台功能。

HTTP功能顧名思義就是「可以從標準HTTP請求中調用HTTP函數」,常見HTTP請求方法的處理(如GET,PUT,POST,DELETE和OPTIONS),Cloud Function都可以支持。

  1. 建立main.py
    首先,自行打開空白的Python檔,創建一個檔名為main.py的檔案,並且移至自行建立的專案資料夾(後續以myfunction/代稱)

    ​​​​# 要處理HTTP,Cloud Functions在每個運行時使用特定的HTTP框架: ​​​​# 而Python使用的框架為flask ​​​​from flask import escape ​​​​# HTTP功能 ​​​​def hello_http(request): ​​​​ """HTTP Cloud Function. ​​​​ Args: ​​​​ request (flask.Request): The request object. ​​​​ <http://flask.pocoo.org/docs/1.0/api/#flask.Request> ​​​​ Returns: ​​​​ The response text, or any set of values that can be turned into a ​​​​ Response object using `make_response` ​​​​ <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>. ​​​​ """ ​​​​ request_json = request.get_json(silent=True) ​​​​ request_args = request.args ​​​​ if request_json and 'name' in request_json: ​​​​ name = request_json['name'] ​​​​ elif request_args and 'name' in request_args: ​​​​ name = request_args['name'] ​​​​ else: ​​​​ name = 'World' ​​​​ return 'Hello {}!'.format(escape(name)) ​​​​# 後台功能 ​​​​def hello_background(data, context): ​​​​ """Background Cloud Function. ​​​​ Args: ​​​​ data (dict): The dictionary with data specific to the given event. ​​​​ context (google.cloud.functions.Context): The Cloud Functions event ​​​​ metadata. ​​​​ """ ​​​​ if data and 'name' in data: ​​​​ name = data['name'] ​​​​ else: ​​​​ name = 'World' ​​​​ return 'Hello {}!'.format(name)
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
    詳細介紹可參考官方教學:
    1. HTTP功能 https://cloud.google.com/functions/docs/writing/http
    2. 後台功能 https://cloud.google.com/functions/docs/writing/background

第三步:下載依附元件

有兩種方式可以指定以 Python 編寫的 Cloud Functions 依附元件,使用其中一種即可:

  1. 使用 pip 套裝管理員的requirements.txt檔案
    例如可創建該檔案後,輸入下列字串(前為套件名稱,後為版本名稱),如果有需要更改使用工具也可以依據自己的使用需求來做改變,但請務必以格式套件名稱==版本名稱來做輸入。

    ​​​​click==6.7
    ​​​​Flask==1.0.2
    ​​​​itsdangerous==0.24
    ​​​​Jinja2==2.10
    ​​​​MarkupSafe==1.0
    ​​​​pip==18.0
    ​​​​requests==2.19.1
    ​​​​setuptools==40.2.0
    ​​​​Werkzeug==0.14.1
    ​​​​wheel==0.31.1
    
  2. 與函式一起封裝本機依附元件

    • 打開cmd,輸入pip install -t DIRECTORY DEPENDENCY
    • 移至DIRECTORY資料夾,開啟名為__init__.py的檔案
    • 於檔案開頭加上import DIRECTORY.DEPENDENCY

    最後資料夾的目錄型態如下:

    ​​​​myfunction/
    ​​​​├── main.py
    ​​​​└── DIRECTORY/
    ​​​​    ├── __init__.py
    ​​​​    └── myscript.py
    
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
    參考資料: https://cloud.google.com/functions/docs/writing/specifying-dependencies-python

第四步:使用gcloud進行函式部署

  1. 開啟cmd,並將路徑設置為myfunction/目錄下,以下述格式進行函式部署

    ​​​​gcloud functions deploy NAME --runtime RUNTIME TRIGGER [FLAGS...]
    
  2. 例如此教學函式名稱為hello_http,以python3.7觸發條件為http進行建置,則輸入:

    ​​​​gcloud functions deploy hello_http --runtime python37 --trigger-http
    
  3. 若還想多指定region與memory,則輸入如下:(可自行變化)

    ​​​​gcloud functions deploy hello_http --runtime python37 --trigger-http --region europe-west1 --memory 512mb
    

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
    小提醒:若出現錯誤訊息為ERROR: (gcloud.functions.deploy) OperationError: code=3, message=Function load error: File main.py that is expected to define function doesn't exist,則請務必檢查所有檔案之路徑與cmd設定之路徑是否正確

    最後,若部署成功cmd會出現下述畫面:

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

    並且開啟firebase後,Cloud Function會新增下圖函數
    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →

    Image Not Showing Possible Reasons
    • The image file may be corrupted
    • The server hosting the image is unavailable
    • The image path is incorrect
    • The image format is not supported
    Learn More →
    詳細介紹可參考官方教學:
    1. 從本地計算機部署 https://cloud.google.com/sdk/gcloud/reference/functions/deploy
    2. gcloud functions deploy https://cloud.google.com/sdk/gcloud/reference/functions/deploy

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
主要參考資料:https://cloud.google.com/functions/docs/writing/