如何获取firebase数据?

2024-03-29 12:09:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python和firebase还不熟悉,我正在尝试清空firebase数据库。

我有一个这种格式的数据库

enter image description here

每只猫都有成千上万的数据。我只想把猫的名字取出来,然后把它们排成一个数组。例如,我希望输出为['cat1','cat2'…]

我在用这个教程 http://ozgur.github.io/python-firebase/

from firebase import firebase
firebase = firebase.FirebaseApplication('https://your_storage.firebaseio.com', None)
result = firebase.get('/Data', None)

上面代码的问题是它将尝试获取数据下的所有数据。我怎么能只拿“猫”?


Tags: 数据iogithubnone数据库http格式教程
3条回答

如果要将cats中的值作为列获取,请尝试使用pyrebase,在cmd/anaconda prompt使用pip install pyrebase(如果没有在环境路径上设置PIP或Python,则稍后会首选)。安装后:

import pyrebase

config {"apiKey": yourapikey
"authDomain": yourapidomain
"databaseURL": yourdatabaseurl,  
"storageBucket": yourstoragebucket,  
"serviceAccount": yourserviceaccount
}

注意:您可以在Firebase的控制台上找到上述所有信息: https://console.firebase.google.com/project/>>>>您的项目>>>>单击带有“将firebase添加到web应用程序”标记的图标“<;'/>;”

回到代码。。。

创建一个整洁的定义,以便将其存储到py文件中:

def connect_firebase():
# add a way to encrypt those, I'm a starter myself and don't know how
username: "usernameyoucreatedatfirebase"
password: "passwordforaboveuser"

    firebase = pyrebase.initialize_app(config)
    auth = firebase.auth() 

    #authenticate a user > descobrir como não deixar hardcoded
    user = auth.sign_in_with_email_and_password(username, password)

    #user['idToken']
    # At pyrebase's git the author said the token expires every 1 hour, so it's needed to refresh it
    user = auth.refresh(user['refreshToken'])

    #set database
    db = firebase.database()

    return db

好的,现在把它保存到一个整洁的.py文件中

接下来,在您的新笔记本或main.py上,您将导入这个新的.py文件,从现在起我们将调用它auth.py。。。

from auth import *

# add do a variable
db = connect_firebase()

#and now the hard/ easy part that took me a while to figure out:
# notice the value inside the .child, it should be the parent name with all the cats keys
values = db.child('cats').get()

# adding all to a dataframe you'll need to use the .val()  
data = pd.DataFrame(values.val())

就是这样,print(data.head())来检查值/列是否在预期的位置。

我在研究pyrebase文档。因此,我们只能从某些路径中提取密钥。

To return just the keys at a particular path use the shallow() method.

all_user_ids = db.child("users").shallow().get()

在你的情况下,会是这样的:

firebase = pyrebase.initialize_app(config)
db = firebase.database()

allCats = db.child("data").shallow().get()

如果没用就告诉我。

Firebase实时数据库是one big JSON tree

when you fetch data at a location in your database, you also retrieve all of its child nodes.

最佳实践是denormalize your data,为同一数据创建多个位置(节点):

Many times you can denormalize the data by using a query to retrieve a subset of the data

在您的例子中,您可以创建名为“categories”的第二个节点,其中您只列出类别名称。

/cat1
    /...
/cat2
    /...
/cat3
    /...
/cat4
    /...
/categories
   /cat1
   /cat2
   /cat3
   /cat4

在这种情况下,可以使用update() method同时写入多个位置。

相关问题 更多 >