导入时覆盖常量

时间:2016-11-15 08:41:49

标签: python python-2.7

所以我一直试图理解类常量的用法,但我不知道如何覆盖它。如果我的图书馆看起来像这样:

class ArcsightLogger(object):
    """
    Main Class to interact with Arcsight Logger REST API
    """

    TARGET = 'https://SOMETHING:9000'

    def __init__(self, username, password, disable_insecure_warning=False):
        """
        Log in the user whose credentials are provided and
        store the access token to be used with all requests
        against Arcsight
        """

        action = 'ignore' if disable_insecure_warning else 'once'
        warnings.simplefilter(action, InsecureRequestWarning)
        r = self._post(
            '/core-service/rest/LoginService/login', data={
                'login': username,
                'password': password,
            }, is_json=False)
        r.raise_for_status()
        loginrequest = untangle.parse(r.content)
        self.token = loginrequest.ns3_loginResponse.ns3_return.cdata

    def format_time(self, *args):
        currentdt = datetime.datetime.now(pytz.utc)
        if len(args) > 0:
            currentdt += datetime.timedelta(*args)
        (dt, micro) = currentdt.strftime('%Y-%m-%dT%H:%M:%S.%f').split('.')
        tz_offset = currentdt.astimezone(tzlocal()).strftime('%z')
        tz_offset = "Z" if tz_offset == "" else tz_offset[:3] + ":" + tz_offset[3:]

        dt = "%s.%03d%s" % (dt, int(micro) / 1000, tz_offset)
        return dt

    def _post(self, route, data, is_json=True, ):
        """
        Post Call towards Arcsight Logger
        :param route: API endpoint to fetch
        :param is_json: Checks if post needs to be JSON
        :param data: Request Body
        :return: HTTP Response
        """

        if not data:
            return

        url = self.TARGET + route
        if is_json:
            return requests.post(url, json=data, verify=False)
        else:
            return requests.post(url, data, verify=False)

这很好用,如果我在这个脚本中手动设置TARGET,但当我导入到另一个脚本时,如下所示:

import arcsightrest

arcsight = arcsightrest.ArcsightLogger('admin', 'somepassword', False)
arcsight.TARGET = 'https://10.10.10.10:9000'
with arcsight.search('query') as search:
    search.wait()
    data = search.events(custom=True)
    print data

然后当我运行脚本时,我发现TARGET从未被实际覆盖,因为Traceback仍然声明它正在使用此调用的 init 函数中的旧TARGET(调用_post) :

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    arcsight = arcsightrest.ArcsightLogger('admin', 'somepassword', False)
  File "/var/www/Projects2/ArcsightSDK/arcsightrest.py", line 37, in __init__
    }, is_json=False)
  File "/var/www/Projects2/ArcsightSDK/arcsightrest.py", line 69, in _post
    return requests.post(url, data, verify=False)
  File "/usr/lib/python2.7/site-packages/requests/api.py", line 110, in post
    return request('post', url, data=data, json=json, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/api.py", line 56, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 596, in send
    r = adapter.send(request, **kwargs)
  File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 487, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='something', port=9000): Max retries exceeded with url: /core-service/rest/LoginService/login (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x1e59e50>: Failed to establish a new connection: [Errno -2] Name or service not known',))

2 个答案:

答案 0 :(得分:1)

在创建实例

之后,您将覆盖变量
arcsight = arcsightrest.ArcsightLogger('admin', 'somepassword', False)
#__init__ has been already done

arcsight.TARGET = 'https://10.10.10.10:9000'

所以在__init__函数中它具有旧值。您需要使用类而不是实例来更改变量

import arcsightrest

arcsightrest.ArcsightLogger.TARGET = 'https://10.10.10.10:9000'

答案 1 :(得分:1)

由于您希望为不同的实例使用不同的目标,因此请使用实例变量,而不是类变量。毕竟,如果它发生变化,它并不是一个常数。

您可以在__init__()方法中传递URL目标的值。如果有合适的值,请使用默认值:

class ArcsightLogger(object):
    """
    Main Class to interact with Arcsight Logger REST API
    """

    def __init__(self, username, password, disable_insecure_warning=False, target='https://SOMETHING:9000'):
        self.target = target
        # etc...

然后在self.target中使用_post()

如果您不想在__init__()方法的参数中设置默认值,那么您可以将默认值定义为类变量并使用它来初始化self.target:< / p>

class ArcsightLogger(object):
    """
    Main Class to interact with Arcsight Logger REST API
    """

    TARGET = 'https://SOMETHING:9000'

    def __init__(self, username, password, disable_insecure_warning=False, target=None):
        self.target = target if target is not None else self.TARGET