Last active
May 5, 2020 01:11
-
-
Save drheinheimer/784f8e7cffcb9a6aff38d8257510ad7f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import json | |
class Hydra(object): | |
""" | |
Example: | |
# Set up the class | |
hydra = Hydra('https://www.openagua.org/hydra', api_key=os.environ['OPENAGUA_SECRET_KEY']) | |
# Method 1: hydra.call(function, **kwargs) | |
resp1 = hydra.call('get_project', project_id=123) | |
# Method 2: hydra.func_name(**kwargs) | |
resp2 = hydra.get_project(project_id=123) | |
""" | |
username = None | |
password = None | |
def __init__(self, endpoint_url, username='', password=None, api_key=None): | |
self.key = api_key | |
if endpoint_url[-1] != '/': | |
endpoint_url += '/' | |
self.endpoint = endpoint_url | |
self.username = username | |
self.password = password or api_key | |
def call(self, func, dict_kwargs=None, **kwargs): | |
if dict_kwargs is not None: | |
return self._call(func, **dict_kwargs) | |
else: | |
return self._call(func, **kwargs) | |
def _call(self, func, *args, **kwargs): | |
payload = {} | |
if args: | |
payload['args'] = list(args) | |
payload['kwargs'] = kwargs | |
endpoint = self.endpoint + func | |
resp = requests.post(endpoint, auth=(self.username, self.password), json=payload) | |
try: | |
return json.loads(resp.content.decode()) | |
except: | |
return resp.content.decode() | |
def __getattr__(self, name): | |
def method(*args, **kwargs): | |
if name == 'call': | |
return self._call(*args, **kwargs) | |
else: | |
return self._call(name, *args, **kwargs) | |
return method |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here are four example uses to call the function. Each of the examples below are functionally equivalent.