导入时覆盖常量

马吕斯

因此,我一直在尝试了解类常量的用法,但我不知道如何将其覆盖。如果我的图书馆看起来像这样:

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函数(调用_post)中使用的是旧TARGET

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',))
安科维奇

创建实例后,您将覆盖变量

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'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章