Skip to content

Commit

Permalink
add besapi class magic methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jgstew committed Nov 18, 2021
1 parent bcd08dd commit 6c0e9aa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/besapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@

from . import besapi

__version__ = "1.0.5"
__version__ = "1.0.6"
40 changes: 36 additions & 4 deletions src/besapi/besapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ def __init__(self, username, password, rootserver, verify=False):
# disable SSL warnings
requests.packages.urllib3.disable_warnings() # pylint: disable=no-member

self.username = username
self.session = requests.Session()
self.session.auth = (username, password)

Expand All @@ -59,8 +60,30 @@ def __init__(self, username, password, rootserver, verify=False):
self.rootserver = rootserver
self.verify = verify

if not self.login():
self.get("login").request.raise_for_status()
self.login()

def __repr__(self):
"""object representation"""
# https://stackoverflow.com/a/2626364/861745
return f"Object: besapi.BESConnction( username={self.username}, rootserver={self.rootserver} )"

def __eq__(self, other):
if (
self.rootserver == other.rootserver
and self.session.auth == other.session.auth
and self.verify == other.verify
):
return True
return False

def __del__(self):
"""cleanup on deletion of instance"""
self.logout()
self.session.auth = None

def __bool__(self):
"""get true or false"""
return self.login()

def url(self, path):
"""get absolute url"""
Expand Down Expand Up @@ -130,13 +153,19 @@ def session_relevance_string(self, relevance, **kwargs):
rel_result_array = self.session_relevance_array(relevance, **kwargs)
return "\n".join(rel_result_array)

def connected(self):
"""return true if connected"""
return bool(self.get("login").request.status_code == 200)

def login(self):
"""do login"""
return bool(self.get("login").request.status_code == 200)
if not self.connected():
self.get("login").request.raise_for_status()

return self.connected()

def logout(self):
"""clear session and close it"""
self.session.auth = None
self.session.cookies.clear()
self.session.close()

Expand Down Expand Up @@ -201,6 +230,9 @@ def export_site_contents(
bes_file.write(content.text.encode("utf-8"))

__call__ = login
# https://stackoverflow.com/q/40536821/861745
__enter__ = login
__exit__ = logout


class RESTResult:
Expand Down

0 comments on commit 6c0e9aa

Please sign in to comment.