Reputation: 196
So i have been trying to understand the usage of a class constant, but i don't see how this can be overwritten. If my library look like this:
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)
This works just fine, if i manually set TARGET in this script, but when i import to another script, like this:
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
Then when i run the script, i see that TARGET is never actually overwritten, because the Traceback still states that it is using the old TARGET in the init function of this call (which calls _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',))
Upvotes: 0
Views: 184
Reputation: 87064
Since you want to use a different target for different instances use an instance variable, not a class variable. After all, it's not really a constant if it's going to change.
You can pass the value for the URL target in the __init__()
method. Use a default value if there is an appropriate one:
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...
Then use self.target
in _post()
.
If you don't like setting the default in the __init__()
method's argument then you can define a default value as a class variable and use it to initialise self.target
:
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
Upvotes: 1
Reputation: 13571
You are overriding variable after creating it's instance
arcsight = arcsightrest.ArcsightLogger('admin', 'somepassword', False)
#__init__ has been already done
arcsight.TARGET = 'https://10.10.10.10:9000'
so in the __init__
function it has the old value. You need to change variable by using class not the instance
import arcsightrest
arcsightrest.ArcsightLogger.TARGET = 'https://10.10.10.10:9000'
Upvotes: 1