繁体   English   中英

Python:无法从不同的模块/功能访问 class 属性

[英]Python: cannot access class attribute from different modules/functions

我有一个名为 Org 的 class,我试图从多个函数(在类外部定义)访问它的方法。 我首先调用main() ,然后是discover_buildings() main()执行没有错误,但是,我在调用discover_buildings()后得到AttributeError: 'Org' has no attribute 'headers'错误。 我做错了什么? (我期待headers属性在不同的方法之间共享)

class Org(object):

    def __init__(self, client_id, client_secret, grant_type='client_credentials'):
        self.grant_type = grant_type
        self.client_id = client_id
        self.client_secret = client_secret
        self.url = CI_A_URL

    def auth(self):
        """ authenticate with bos """
        params = {
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'grant_type': self.grant_type
        }
        r = requests.post(self.url + 'o/token/', data=params)
        if r.status_code == 200:
            self.access_token = r.json()['access_token']
            self.headers = {
                'Authorization': 'Bearer %s' %self.access_token,
                'Content-Type': 'application/json',
            }
        else:
            logging.error(r.content)
            r.raise_for_status()

    def get_buildings(self, perPage=1000):
        params = {
            'perPage': perPage
        }

        r = requests.get(self.url + 'buildings/', params=params, headers=self.headers)
        result = r.json().get('data')
        if r.status_code == 200:
            buildings_dict = {i['name']: i['id'] for i in result}
            sheet_buildings['A1'].value = buildings_dict
        else:
            logging.error(r.content)
            r.raise_for_status()


client_id = 'xxx'
client_secret = 'yyy'
gateway_id = 123
o = Org(client_id, client_secret)

def discover_buildings():
    return o.get_buildings()

def main():
    return o.auth()

在此先感谢您的帮助!

问题是您定义“discover_buildings”的方式,您首先用“o”定义它,而不是在身份验证之后初始化。

处理这个:

  1. 重写discover以'o'作为参数

    或者

  2. 如果没有验证“o”,请先检查“o”是否有“标题”并执行 rest

     def discover_buildings(): if not getattr(o, 'headers'): o.auth() return o.get_buildings()

尝试在需要时使用属性来计算标头,然后将其缓存。


    def auth(self):
        """ authenticate with bos """
        #  👇you might want to isolate `token` into a nested @property token
        params = {
            'client_id': self.client_id,
            'client_secret': self.client_secret,
            'grant_type': self.grant_type
        }

        # note assignment to `_headers`, not `headers`



        r = requests.post(self.url + 'o/token/', data=params)
        if r.status_code == 200:
            self._access_token = r.json()['access_token']


        #  👆 
            self._headers = { # 👈
                'Authorization': 'Bearer %s' %self._access_token,
                'Content-Type': 'application/json',
            }
        else:
            logging.error(r.content)
            r.raise_for_status()

    #cache after the first time.
    _headers = None
    
    @property
    def headers(self):
        """ call auth when needed
        you might want to isolate `token`
        into its own property, allowing different
        headers to use the same token lookup
        """
        if self._headers is None:
            self.auth()
        return self._headers
    

您没有定义self.headers 您需要在运行 o.get_buildings() 之前运行o.auth() (或定义self.headers o.get_buildings()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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