วิธีติดตั้ง Firebase Admin SDK
เปิด command / terminal ขึ้นมา แล้ว พิมพ์คำสั่งตามนี้ (ตัวอย่างนี้จะทำในระบบปฏิบัติการ Windows นะ)
โค้ด: เลือกทั้งหมด
pip install --upgrade firebase-admin
การตั้งค่า Project
- คลิกที่ icon "ฟันเฟือง" >> Project setting ตามรูป
- คลิกที่ Service accounts >> Firebase Admin SDK >> Python >> Generate new private key
- สร้างไฟล์ python 1 ไฟล์ แล้วย้าย private key มาอยู่ด้วยกัน ภายในไฟล์ python จะมีโค้ดตามนี้ ในตัวอย่างชื่อไฟล์ จะเป็น add_data.py
โค้ดนี้ต้องอยู่ก่อนโค้ดเพิ่มข้อมูล เท่านั้นไฟล์ python ชื่อไฟล์ จะเป็น add_data.pyโค้ด: เลือกทั้งหมด
import firebase_admin from firebase_admin import credentials from firebase_admin import firestore # Use a service account cred = credentials.Certificate('private-key.json') # edit code here replace private-key.json with your private key firebase_admin.initialize_app(cred) db = firestore.client()
ไฟล์ private key จะเป็น test-83205-firebase-adminsdk-i50tj-804216b64f.json
วิธีการ insert data ใน Firebase(Cloud Firestore) ด้วย Python3
- การเพิ่ม document โดยกำหนด document id เอง
ตัวอย่างโค้ดอ้างอิงตำแน่งของ collection ชื่อ users และ document id เป็น eieiโค้ด: เลือกทั้งหมด
# referring from users's collection and document.id = 'eiei' users_ref = db.collection('users').document('eiei') users_ref.set( # add a document from users_ref { 'name': 'ada', # field name = 'name', value = 'ada' 'lastname': 'wong' # field name = 'lastname', value = 'wong' } )
ใน function set parameter จะมีตัวเดียว เป็น dictionary
ref.set(dict) <-- ประมาณนี้
ใน dict ประกอบด้วย key: value
key : เป็น field name เป็น type string เท่านั้น
value : เป็นค่าของ field นั้น สามารถเป็น type string, list(array), int, dictionary(map), null, timestamp, geopoint, reference
- การเพิ่ม document โดยไม่กำหนด document id (Firestore สุ่มให้)
ตัวอย่างโค้ดโค้ด: เลือกทั้งหมด
users_ref = db.collection('users').document() # random document.id users_ref.set( # add a document from users_ref { 'name': 'pb', # field name = 'name', value = 'pb' 'lastname': 'ggez', # field name = 'lastname', value = 'ggez' 'array_count': [1,2,3,4,5] # field name = 'array_count', value = [1,2,3,4,5] } )
สรุป
ใน Firebase Firestoreการเพิ่มข้อมูลไม่จำเป็นต้อง มีชื่อ field name เหมือนกันหมดทุก document id แต่ถ้าไม่จำเป็นต้องทำให้แตกต่างกันก็ตั้ง field name ให้เหมือนกันเถอะ เพราะตอนอ่านข้อมูลจะสับสนและยากขึ้น
ใน function set() จะมีพารามิเตอร์ตัวเดียวเป็น dictionary โดย key : field_name(string only), value: ??? สามารถใส่ได้ครั้งละหลาย field ถ้าอยากให้ใส่หลาย document ก็วน loop ใส่ สุดท้ายการกำหนดสิทธ์จะเหมือนกับบทความก่อน
อ้างอิง
https://www.mindphp.com/%E0%B8%84%E0%B8%B9%E0%B9%88%E0%B8%A1%E0%B8%B7%E0%B8%AD/73-%E0%B8%84%E0%B8%B7%E0%B8%AD%E0%B8%AD%E0%B8%B0%E0%B9%84%E0%B8%A3/3921-what-is-firebase-backend.html
https://www.mindphp.com/forums/viewtopic.php?f=144&t=79861
https://www.mindphp.com/forums/viewtopic.php?f=144&t=79787
https://www.mindphp.com/forums/viewtopic.php?f=144&t=79846