我想使用python(firebase_admin
)而不是pyrebase
或python-firebase
的官方库通过Firebase数据库检索一些数据。
我尝试执行以下代码行:
from firebase_admin import db
from firebase_admin import credentials
import firebase_admin
cred = credentials.Certificate('https://project_name.firebaseio.com/.json')
firebase_admin.initialize_app(cred)
result = db.Query.get()
但随后出现以下错误:
FileNotFoundError: [Errno 2] No such file or directory: 'https://project_name.firebaseio.com/.json'
即使当我在浏览器中输入此url(用我的真实项目名称替换
project_name
)时,我仍从数据库中获取数据的json。如何解决此错误?
最佳答案
Certificate
应指向带有您的凭据/证书的本地文件。相反,您将其指向您的数据库URL(这不是本地文件),因此库将引发错误。
从documentation on initializing the Python SDK:
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db
# Fetch the service account key JSON file contents
cred = credentials.Certificate('path/to/serviceAccountKey.json')
# Initialize the app with a service account, granting admin privileges
firebase_admin.initialize_app(cred, {
'databaseURL': 'https://databaseName.firebaseio.com'
})
# As an admin, the app has access to read and write all data, regardless of Security Rules
ref = db.reference('restricted_access/secret_document')
print(ref.get())