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 1 - 使用Python建置Firestore ###### tags: `GCP` `Firestore` `Python` [TOC] --- ## ==一、簡介== 簡單來說, Cloud Firestore 是一個快速、完全託管的檔案導向 NoSQL 資料庫。不像 SQL 資料庫有 table、rows,Cloud Firestore 的資料都是存在檔案 (document),而這些檔案則是以資料夾 (collection)。每個檔案是以 key-value 做儲存資料的格式。 :::warning :bulb: 小提醒:NoSQL 是 "Not only SQL" 的意思,也就是可以做到 **"不只是個資料庫"** 的功能 ::: ###### :book: 參考資料: https://blog.gcp.expert/cloud-firestore-cloud-native-nosql-introduction/ --- ## ==二、前置作業== 需先於cmd執行下列指令 - <code color=red>pip install python-firebase</code> - <code>pip install firebase-admin</code> :::warning :bulb: 小提醒: 若在cmd內輸入上述指令後顯示「'pip' 不是內部或外部命令、可執行的程式或批次檔。」 可參考 [不錯的教學](http://alex9ufoexploer.blogspot.com/2017/10/python-pip.html) ::: --- ## ==三、專案設置== ### 步驟一:建立專案 ![](https://i.imgur.com/ufiGAqj.png) ### 步驟二:建立資料庫 分為「鎖定模式」與「測試模式」: - 「鎖定模式」:系統會拒絕所有第三方的讀寫作業 - 「測試模式」:可以使用第三方程序來進行所有讀寫作業 ![](https://i.imgur.com/M7Lp3Wx.png) 不論選擇哪一種,後續都能於 **Database->規則** 處更改權限為```true```或```false``` ![](https://i.imgur.com/gCXKhrv.png) ### 步驟三:設置私密金鑰 此步驟主要是供 **本機端** 使用,如果沒有獲得金鑰就不能對從本機端透過 Python、JavaScript...等程式語言來對 firestore 的資料做更改。 :::warning :bulb: 小提醒:如果後續要使用到 Cloud Function 的話則不需要此步驟,初學者的話還是建議先從 **本機端** 來做練習。(關於 Cloud Function 的資訊可參考 [第五章 - Cloud Function的入門與部署](https://hackmd.io/yn10QCzJS8yqbe8twZGCFQ)) ::: 首先於左上角齒輪處點選專案設定,選擇服務帳戶後,將箭頭勾至Python,並按下產生新的私密金鑰,流程整理如下: - 齒輪->專案設定->服務帳戶->勾選Python->產生私密金鑰 ![](https://i.imgur.com/Ht29fcE.png) - 複製程式碼,貼至Python習慣的IDE中,並更改cred中的路徑 ![](https://i.imgur.com/8S9lqqw.png) ### 步驟四:集合與文件 主要可分為: - <code>set()</code>:新增 - <code>update()</code>:修改 - <code>get()</code>:查詢 - <code>delete()</code>:刪除 :::warning :bulb: 小提醒:```set()``` 與 ```update()``` 的差異在於,如果更改資料用 ```set()``` ,則全部欄位與資訊都要列上去, ```update()``` 可直接針對裡面某個欄位的值下去修改 ::: 以下將直接舉例,除了一、新增為完整的程式碼外(涵蓋設置金鑰和建立集合與文件部分),後面三者為補充的程式碼 --- ## ==四、Firestore 資料更改基礎== ### (一)新增 ```python= #####################一定需要,且一段程式碼只能出現一次#################### import firebase_admin # 用來認證 from firebase_admin import credentials # path/to/serviceAccount.json 須改為自己的金鑰路徑 cred = credentials.Certificate("path/to/serviceAccount.json") firebase_admin.initialize_app(cred) # 用來存放資料 from firebase_admin import firestore db = firestore.client() ######################################################################## # collectio為集合,document為要寫入的文件 student1 = db.collection('Q1').document('DOC2') student1.set({ '姓名': '西野', '年齡': '23', '學號': '123456789' }) # 用來提醒自己已經新增好資料 print('Done') ``` 打開firebase,就能看到自己剛剛建立的資料 ![](https://i.imgur.com/uXjjsPM.png) :::warning :bulb:小提醒 - 第11列程式碼如果打 <code> student1 = db.collection('Q1',"DOC1","Q2").document('DOC2')</code> 就是在「集合Q1」內的「DOC1文件」中的「集合Q2」中的「DOC2文件」中新增資料,也就代表使用者可以自己製造階層來存放資料,就像「資料夾中的資料夾」一樣。 - 也可寫為 ```student1 = db.collection("Q1/DOC1/Q2").document('DOC2')``` 或 ```student1 = db.document("Q1/DOC1/Q2/DOC2")``` - 若15列程式碼改為 <code>student1 = db.collection('Q1').document()</code> ,則不限定有幾份document,也就是每次執行,系統都會幫忙產生一個隨機名稱的dcoument,很方便,很適合用在迴圈,執行多次後的結果如下圖 ![](https://i.imgur.com/2oPyhBS.png =300x) ::: ### (二)修改 ```python= # Update Document student1.update({ '年齡': '24' }) ``` 即得到下圖(年齡變為24): ![](https://i.imgur.com/EbUk8nE.png =x300) ### (三)查詢 id為文件名稱,to_dict()為裡面的內容 ```python= # Get Collection get_collection = db.collection("Q1").get() for doc in get_collection: print(u'{} => {}'.format(doc.id, doc.to_dict())) # Get Doc get_doc = db.collection('Q1').document('DOC2').get() # 若要查詢student1文件,則可以直接改為get_doc = student1.get() print('姓名 => {}'.format(doc.to_dict()['姓名'])) print('學號 => {}'.format(doc.to_dict()['學號'])) print('年齡 => {}'.format(doc.to_dict()['年齡'])) ``` 即得到下圖執行結果: ![](https://i.imgur.com/DIWw5UU.png =500x) ### (四)刪除 在此先隨意創建相同路徑之第二份文件 ![](https://i.imgur.com/azyacTS.png) 先使用 ```get()``` 獲取 collection 或 doc 的資料,再以迴圈刪除 (因為同一個文件裡可能有好幾筆資料同時有某個值,所以才要用迴圈) :::danger :exclamation: 2019 年年底使用 `db.collection("Q1").get()` 已經無效,要更改為 `db.collection("Q1").stream()` ::: ```python= # Get Collection get_collection = db.collection("Q1").get() # Delete Collection for delete_list in get_collection: doc_del = db.collection('Q1').document(delete_list.id) doc_del.delete() # 刪除document print('Delete Doc: {} Complete.'.format(delete_list.id)) ``` 即得到下圖結果: (Q1集合的所有文件遭刪除,因為Q1內不再有文件,所以連Q1都消失) ![](https://i.imgur.com/T22ygD9.png =700x300) 若路徑不相同,則文件則不會被刪除: (DOC1的創建路徑為<code class=blue>db.collection('Q1', 'DOC1', 'Q2').document('DOC2')</code>) ![](https://i.imgur.com/jXpDlG6.png =700x300) :::warning :bulb:小提醒:程式碼為方便教學都打<code>student1 = db.collection('Q1').document('DOC2')</code>, 但其實建議改為<code>student1_ref = db.collection('Q1').document('DOC2')</code>,來代表參照位置 例如查詢資料,就打<code>student1_ref.get()</code>即可。 ::: ###### :book: 參考資料: ###### 1. https://medium.com/pyradise/10%E5%88%86%E9%90%98%E8%B3%87%E6%96%99%E5%BA%AB%E6%93%8D%E4%BD%9C-%E6%96%B0%E5%A2%9E%E8%B3%87%E6%96%99-b96db385e1e4 ###### 2. https://mks.tw/2675/%E3%80%8C%E5%AD%B8%E7%BF%92%E6%97%A5%E8%AA%8C%E3%80%8Dcloud-firestore-%E5%9F%BA%E6%9C%AC%E6%96%B0%E5%A2%9E%E3%80%81%E6%9F%A5%E8%A9%A2%E3%80%81%E5%88%AA%E9%99%A4%E5%88%9D%E9%AB%94%E9%A9%97-python

    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