我想通过firebase数据库使用python(firebase_admin
)的官方库而不是pyrebase
或python-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'
即使我在浏览器上输入此网址(project_name
替换为我的真实项目名称),我也会从数据库中获取数据的json。
如何解决此错误?
答案 0 :(得分:1)
Certificate
应指向包含凭据/证书的本地文件。您将其指向您的数据库URL,该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())
答案 1 :(得分:0)
试试这个,这对我有用
<块引用>import os
from firebase_admin import credentials, firestore, initialize_app
# Initialize Firestore DB
data = os.path.abspath(os.path.dirname(__file__)) + "/serviceAccountKey.json"
cred = credentials.Certificate(data)
default_app = initialize_app(cred)
db = firestore.client()