首页 > 解决方案 > 当我尝试打印登录用户的 localID 时,它不起作用

问题描述

我终于找到了如何从我的 firebase 类访问 localId 实例,但是现在当用户登录并尝试打印 localId 时,对象返回为 none。当我尝试在 firebase 类中打印它时,它会返回值,但在类之外它不起作用。这是我的firebase类。

class MyFireBase():

    def __init__(self):
        # initialize localId to None, just to be sure it always exists
        self.localId = None


    def sign_up(self, email, password):

            app = App.get_running_app()
            email = email.replace("\n","")
            password = password.replace("\n","")

            # Send email and password to Firebase
            # Firebase will return localId, authToken (idToken), refreshToken
            signup_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=" + self.wak
            signup_payload = {"email": email, "password": password, "returnSecureToken": True}
            sign_up_request = requests.post(signup_url, data=signup_payload)
            sign_up_data = json.loads(sign_up_request.content.decode())
            print(sign_up_request.ok)
            print(sign_up_request.content.decode())


            if sign_up_request.ok == True:
                print(sign_up_data)
                refresh_token = sign_up_data['refreshToken']

                self.localId = sign_up_data['localId']
                idToken = sign_up_data['idToken']

                # Save refreshToken to a file
                with open(app.refresh_token_file, "w") as f:
                    f.write(refresh_token)


                app.local_id = self.localId
                app.id_token = idToken




                my_data =  '{"avatar": "profilepic.png", "jobs_done": "", "jobs_posted": ""}'
                post_request = requests.patch("https://moonlighting-bb8ab.firebaseio.com/users/" + self.localId + ".json?auth=" + idToken, data=my_data)
                print(post_request.ok)
                print(post_request.content.decode())

                app.root.current = "create"



            elif sign_up_request.ok == False:

                error_data = json.loads(sign_up_request.content.decode())
                error_message = error_data["error"]['message']
                app.root.ids.signup.ids.signup_message.text = error_message.replace("_", " ")

    def send_user_details(self):
        app = App.get_running_app()
        my_data ={"first name": app.root.ids.create.ids.first_name.text, "last name": app.root.ids.create.ids.last_name.text,
                   "phone number": app.root.ids.create.ids.phone_number.text, "job1": app.root.ids.create.ids.job1.text, "job2": app.root.ids.create.ids.job2.text,
                   "job3": app.root.ids.create.ids.job3.text, "date of birth": app.root.ids.create.ids.date_of_birth.text, "state": app.root.ids.create.ids.state1.text}

        user_details = requests.patch("https://moonlighting-bb8ab.firebaseio.com/users/" + app.local_id + ".json?auth=" + app.id_token,  json.dumps(my_data))
        print(user_details.ok)
        print(user_details.content.decode())

        app.root.current = "main"




    def sign_in_existing_user(self, email, password):
        signin_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + self.wak
        signin_payload = {"email": email, "password": password, "returnSecureToken": True}
        signin_request = requests.post(signin_url, data=signin_payload)
        sign_up_data = json.loads(signin_request.content.decode())
        app = App.get_running_app()
        print(signin_request.ok)
        print(signin_request.content.decode())

        if signin_request.ok == True:
            refresh_token = sign_up_data['refreshToken']

            self.localId = sign_up_data['localId']
            idToken = sign_up_data['idToken']
            # Save refreshToken to a file
            with open(app.refresh_token_file, "w") as f:
                f.write(refresh_token)

            # Save localId to a variable in main app class
            # Save idToken to a variable in main app class
            app.local_id = self.localId
            app.id_token = idToken
            # Create new key in database from localId
            # Get friend ID
            # Get request on firebase to get the next friend id
            # --- User exists so i dont need to get a friend id
            # self.friend_get_req = UrlRequest("https://friendly-fitness.firebaseio.com/next_friend_id.json?auth=" + idToken, on_success=self.on_friend_get_req_ok)
            # app.change_screen("home_screen")

            app.root.current = "main"


        elif signin_request.ok == False:
            error_data = json.loads(signin_request.content.decode())
            error_message = error_data["error"]['message']
            app.root.ids.login.ids.login_message.text = error_message.replace("_", " ")

这是我尝试从中打印的课程

class ProfileWindow(Screen):

def on_enter(self, *args):
        print(MyFireBase().localId)

任何帮助将不胜感激

这是 ProfileWindow 的代码


class ProfileWindow(Screen):

    def __int__(self, thefirebase, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.thefirebase = thefirebase


    def on_enter(self, *args):
        print(self.thefirebase.localId)

我将它重命名为 thefirebase,因为我有一个我也使用的模块,称为 firebase。

标签: pythonfirebasefirebase-authenticationkivy

解决方案


当方法被调用时,您在实例上设置localId变量。这意味着如果要检索 ,则需要使用相同的实例。在内部创建一个全新的实例只会返回您的初始值- 这是- 因为尚未在该实例上调用。MyFireBasesign_up()localId MyFireBaseMyFireBaseon_enterlocalIdNonesign_up()

您需要重组代码,以便在ProfileWindow创建时将初始化的MyFireBase实例传递给它。

例如:

class ProfileWindow(Screen):

    def __init__(self, firebase, **kwargs):
        super().__init__(**kwargs)

        self.firebase = firebase  # Store the initialised MyFireBase instance

    def on_enter(self, *args):
        print(self.firebase.localId)  # Use the initialised instance

然后将MyFireBase实例传递给ProfileWindow您创建它时。

firebase = MyFireBase()
firebase.sign_up(...)

...

window = ProfileWindow(firebase)  # Pass the initialised MyFireBase instance

推荐阅读