ph.zeng
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Help
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    {%hackmd @wh91008/theme %} # Lecture 6 - Firestore的監聽(Cloud Funtion) ###### tags: `GCP` `Firestore` `Cloud Function` `Python` [TOC] --- ## ==一、前言== 筆者在 [第四章 - Firestore的監聽(onSnapshot)](https://hackmd.io/8_Z5qQVfTBugi6xlzbQF3Q#%E4%B8%80%E3%80%81%E5%89%8D%E8%A8%80) 已經提過 Firestore 有個非常好用的功能就是 「監聽」,其中其中一個方法是搭配 Cloud Function 進行監聽,此章節就是用來介紹 「Cloud Function 要如何進行監聽?」 前置作業與監聽方法的簡介也可參考第四章,在此不再多做贅述 --- ## ==二、使用Cloud Function 監聽 Firestore== 在不論是使用 [Python](https://hackmd.io/yn10QCzJS8yqbe8twZGCFQ) 或是 [Node.js](https://hackmd.io/vZahd2ElQmmorHGD3GxEug) ,第五章我們已經成功佈署了 Cloud Function 的第一個函數,接著就可以直接透過網頁版的Cloud Function介面來做其他函數的佈署,佈署介面如下: ![](https://i.imgur.com/DQ3xqv3.png =600x) 在使用Cloud Function進行監聽時,有個非常重要的地方就是 **「觸發條件」與「事件類型」** (甚至可以說是進行監聽最重要的一個環節),且一旦部署函式後,將 **不容更改** ,所以請務必在部署之前就先確認好所需使用的條件與事件類型。 ### (一)事件類型 在此將先以觸發條件為Cloud Firestore的情況下,詳述各個事件類型的差異,事件類型分為: - write:寫入 - create:創建 - update:更新 - delect:刪除 如同字面上的意思,當指定的文件路徑(也就是被監聽的地方)發生該事件時,則就會執行 ```main.py``` 中所指定的 **某個函式** 。 ### (二)文件路徑 假設資料結構呈現如下: ![](https://i.imgur.com/tVB6GwE.png) 監聽主要會分為兩個情況: 1. **監聽document** :只監聽某個document(例如match1055)裡的變化,則文件路徑為 ```PlayAndScore/match1055``` 2. **監聽collection** :監聽整個collection裡面的情況,例如要建構遊戲常常會需要增加很多match,則監聽collection就能在一個match產生後執行指定的函式(進行主遊戲、開始紀錄...等),則文件路徑為```PlayAndScore/{隨便輸入但不可以為空或奇怪的符號}```。 ### (三)呼叫函式 在確認好事件類型與監控的文件路徑後,最靈魂的部分就是呼叫函式,首先在```requeirements.txt```中,必須先輸入依附元件的名稱與版本,格式如下: ```python= # Function dependencies, for example: # package>=version requests == 2.18.4 pandas == 0.25.0 firebase-admin == 2.17.0 numpy == 1.17.0 asyncio == 3.4.3 ``` 接著在```main.py```中輸入所有的程式 ```python= # TODO import some packages import asyncio import time import requests import pandas as pd import numpy as np import firebase_admin from firebase_admin import credentials from firebase_admin import firestore import json # TODO use the application default credentials cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred, { 'projectId': '?????', }) # projectId可從 一般設定 獲取 專案專屬識別碼 # TODO function def hello_firestore(event, context): """Triggered by a change to a Firestore document. Args: event (dict): Event payload. context (google.cloud.functions.Context): Metadata for the event. """ resource_string = context.resource # print out the resource string that triggered the function print(f"Function triggered by change to: {resource_string}.") # now print out the entire event object print(str(event)) ``` 最後,就可以在最下方 **要執行的函式** 中輸入該指定函式 :::warning :bulb: 小提醒: 1. 在```main.py```中可以寫入很多function,但最前方要記得import Package與輸入專案認證的部份,且最後執行函式只能寫一個。 2. 函式是否有執行成功,可點擊「測試」確認是否回應ok,若回應ok則前往「查看紀錄」中可觀看相關的紀錄檔,確保函式沒有bug存在。 ::: --- 其他函式實用的補充資訊,可參考至 [第七章 - Cloud Function的延伸應用](https://hackmd.io/SaNljmR7TRy_E8hyoRYXzQ?both),會有更詳細的解釋和持續的更新。

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully