简体   繁体   中英

How to change value in initial in Class() after some change

I have some value initial in class
And in the initial , it will check if the access_token is null,
It need to call get_access_token to update it
But After it update, I print the value print "After change",self.access_token

It is still None
How can I update the value after update the self.oauth_obj , self.access_token ??

class Client():

    def __init__(self):

        obj = Data.objects.get(username="tt")
        self.oauth_obj = obj
        self.url = self.oauth_obj.url
        self.username = self.oauth_obj.username
        self.password = self.oauth_obj.password
        self.access_token = self.oauth_obj.access_token
        self.refresh_token = self.oauth_obj.refresh_token

        print "========="
        print "Before change",self.access_token
        if not obj.access_token:
            self.get_access_token()
        print "After change",self.access_token
        print "========="


    def get_access_token(self):

        url =self.url
        payload = {
            'grant_type': 'password',
            'username': self.username,
            'password': self.password,
        }
        response = requests.post(url, auth=auth, data=payload)
        response_data = response.json()
        access_token = response_data["access_token"]
        refresh_token = response_data["refresh_token"]
        self.oauth_obj.access_token = access_token
        self.oauth_obj.refresh_token = refresh_token
        self.oauth_obj.save()

You are creating local variables. In your get_access_token method, change those lines to assign to self :

def get_access_token(self):
    ...
    self.access_token = response_data["access_token"]
    self.refresh_token = response_data["refresh_token"]
    self.oauth_obj.access_token = self.access_token
    self.oauth_obj.refresh_token = self.refresh_token
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM