首页 > 解决方案 > Pyrebase 和 Firebase 数据库规则,如何用 Python 处理?

问题描述

我是 Firebase 的新手,我使用 Pyrebase 作为 Python 3.7 的库。为了测试这个库,我创建了一个带有公共规则的实时数据库:

// These rules give anyone, even people who are not users of your app,
// read and write access to your database
{
  "rules": {
    ".read": true,
    ".write": true
  }
}

测试 API 很容易。现在,我想在我的案例中引入更多限制性规则:

// These rules grant access to a node matching the authenticated
// user ID from the Firebase auth token
{
  "rules": {
    "users": {
      "$uid": {
        ".read": "$uid === auth.uid",
        ".write": "$uid === auth.uid"
      }
    }
  }
}

但是我遇到了很多问题和疑问。我用于身份验证的 Python 代码是这样的:

        firebase = pyrebase.initialize_app(self.config)
        self.username = email
        self.password = password
        self.db = firebase.database()
        self.auth = firebase.auth()
        # authenticate a user
        self.user = self.auth.sign_in_with_email_and_password(self.username, self.password)

现在,当我尝试阅读某些内容时:

#user_id is the name  of the child of main_document 
db.child(self.main_document).child(user_id).get(self.user['idToken']).val() 

我的数据库结构是这样的: 在此处输入图像描述

从文档中阅读并尝试从规则语法中理解,我发现我需要可以从self.user变量中获取的用户 UID。但是我怎样才能“发送”到 Firebase 以使其有可能进行匹配?我希望我清楚:)

标签: pythonfirebasefirebase-realtime-databasefirebase-securitypyrebase

解决方案


您将需要使用 Firebase 身份验证来登录用户,如 Pyrebase 关于身份验证的文档中所示:firebase.auth().sign_in_with_email_and_password(email, password)

用户登录后,他们的凭据将随每个请求自动发送到 Firebase,Firebase 将按照auth您数据库的安全规则提供这些凭据。


推荐阅读