Last active
January 23, 2024 14:30
-
-
Save e96031413/5c0f6a7402fe07bc58de6b172218f954 to your computer and use it in GitHub Desktop.
使用Python操作Firebase資料庫(CRUD)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
Firebase是可以即時讀取的資料庫,主要以JSON格式為主。除了透過程式操作外,也能在Firebase的網頁界面上進行資料操作(上傳、讀取、修改、刪除) | |
''' | |
###程式1### | |
#引入模組 | |
from firebase import firebase | |
import time | |
#產生資料 | |
new_users = [ | |
{'name': 'Richard Ho','type':1}, | |
{'name': 'Tom Wu','type':1}, | |
{'name': 'Judy Chen','type':0}, | |
{'name': 'Lisa Chang','type':0} | |
] | |
#連接資料庫(由於設定任何人都能存取,所以不需要設定其他的API Key) | |
db_url = 'https://test-e7b86.firebaseio.com' | |
fdb = firebase.FirebaseApplication(db_url, None) | |
#在user下建立四筆資料(來自new_users)(.post新增) | |
for data in new_users: | |
fdb.post('/user', data) | |
time.sleep(3) | |
#在user下查詢新增的資料(.get讀取) | |
users = fdb.get('/user', None) #None全部讀取,1代表讀取第一筆,以此類推 | |
print("資料庫中找到以下的使用者") | |
for key in users: | |
print(users[key]['name']) | |
#整理:使用到的方法Method | |
#result = fdb.post('/user', user) #建立(C) | |
#result = fdb.get('/user',None) #讀取(R) | |
#result = fdb.delete('/user',None) #刪除(D) | |
###程式2### | |
from firebase import firebase | |
key="XXXXXXXXXXXXXXXXX" | |
authentication = firebase.FirebaseAuthentication(key, 'XXX@gmail.com')#進行身分驗證,需要資料庫密鑰和Google資料庫擁有者帳號 | |
firebase.authentication = authentication #身分驗證 | |
user = authentication.get_user() #獲取使用者資訊 | |
firebase = firebase.FirebaseApplication('https://XXXXXX.firebaseio.com/', authentication=authentication) #登入資料庫 | |
#讀取A1的value | |
firebase.get('/ABCD','A1') | |
#讀取所有key value | |
firebase.get('/ABCD',None) | |
#使用firebase.put()設定目錄下的key和value值 | |
firebase.put("/ABCD","AC","1111") | |
#隨機產生key值密免重複 | |
firebase.post("/ABCD","1111") | |
#使用firebase.delete()刪除指定目錄的key值 | |
firebase.delete("/ABCD",'AC') | |
###上傳圖片到Firebase### | |
from google.cloud import storage | |
from firebase import firebase | |
import os | |
os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="filePathTo.json" | |
db_url='https://test-XXXXX.firebaseio.com' # Your project url | |
firebase = firebase.FirebaseApplication(db_url,None) | |
client = storage.Client() | |
bucket = client.get_bucket('test-XXXXX.appspot.com') | |
imageBlob = bucket.blob("/") | |
imagePath = "path/to/dir/" + fileName # Replace with your own path | |
imageBlob = bucket.blob(fileName) | |
imageBlob.upload_from_filename(imagePath) # Upload your image |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment