def test_unicode_handling(self): name = 'ricardobolañossalazar' name = unicode(name.decode('utf-8')) client = Hammock("http://example.org") resp = client.users(name) assert resp._url() client = Hammock(u"http://example.org") resp = client.users(name) assert resp._url()
def __init__(self, username_or_access_token, password=None, spark_api=Hammock('https://api.particle.io'), timeout=30): """Initialise the connection to a Spark Cloud. If you give a user name and password an access token will be requested. The list of known devices attached to your account will be requested. If you have several devices and not all of them are connected it will take a long time to create the object. The Spark Cloud will take ~30 seconds (per device?) to reply as it waits for an answer from the disconnected devices. """ self.spark_api = spark_api if password is None: self.access_token = username_or_access_token else: self.access_token = self._login(username_or_access_token, password) self.spark_api = self.spark_api.v1.devices self.timeout = timeout
def test_methods(self): client = Hammock(self.BASE_URL) for method in ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']: HTTPretty.register_uri(getattr(HTTPretty, method), self.URL) request = getattr(client, method) resp = request('sample', 'path', 'to', 'resource') self.assertEqual(HTTPretty.last_request.method, method)
def __init__(self, **kwargs): if 'api_url' not in kwargs: raise ValueError( 'api_url parameter should be passed to any Web Linker component' ) self.api_url = kwargs['api_url'] self.client = Hammock(self.api_url)
def __init__(self): self.host = os.environ.get('INAWARE_HOST') self.user = os.environ.get('INAWARE_USER') self.password = os.environ.get('INAWARE_PASS') if not self.host or not self.user or not self.password: raise ValueError('No INAWARE_HOST defined in environment.') self.inaware = Hammock(self.host, auth=(self.user, self.password))
def __init__(self, host, path, username, password): url = '{}/{}'.format(host, path) self.agilepoint = Hammock(url, auth=(username, password), headers={'Content-Type': 'application/json'}) self.workflow = Workflow(self) self.admin = Admin(self)
def __init__(self): auth = "ApiKey %s:%s" % (USERNAME, API_KEY) headers = { "Authorization": auth, 'content-type': 'application/json' } self.url = Hammock("%s/%s" % (BASE_URL, VERSION), verify=False, append_slash=True, headers=headers)
def __init__(self, client_id, access_token, api_base_url=API_BASE_URL, api_version=API_VERSION): self.client_id = client_id self.access_token = access_token self.client = Hammock('/'.join( [api_base_url, 'v{}'.format(api_version)]))
def _init_pagerduty(config_file_name): config = _load_config(config_file_name) headers = { 'Authorization': 'Token token={0}'.format(config['pagerduty_token']), 'Content-Type': 'application/json', } pager_duty_client = Hammock('https://{}.pagerduty.com/api/v1/'.format( config['pagerduty_account']), headers=headers) return pager_duty_client
def weatherConditions(key, lat, lon): f = Hammock( 'https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}&units=metric' .format(lat, lon, key)) weather = f.GET().json() current_observation = {} current_observation["temperature"] = weather['main']['temp'] current_observation["condition"] = weather['weather'][0]["main"] current_observation["humidity"] = weather['main']['humidity'] current_observation["cloud_cover"] = weather['clouds']['all'] return current_observation
def ekopost_api(self): if self._ekopost_api is None: verify_ssl = True auth = None if self.app.config.ekopost_api_verify_ssl == 'false': verify_ssl = False if self.app.config.ekopost_api_user and self.app.config.ekopost_api_pw: auth = (self.app.config.ekopost_api_user, self.app.config.ekopost_api_pw) self._ekopost_api = Hammock(self.app.config.ekopost_api_uri, auth=auth, verify=verify_ssl) return self._ekopost_api
def hourly(key, forecast_date, lat, lon): f = Hammock( 'https://api.openweathermap.org/data/2.5/forecast?lat={}&lon={}&appid={}&units=metric' .format(lat, lon, key)) hourly_forecast = f.GET().json() forecasts = hourly_forecast["list"] for forecast in forecasts: h = datetime.fromtimestamp(forecast["dt"]) if h - forecast_date < timedelta(hours=3): return forecast
def navet_api(self): if self._navet_api is None: verify_ssl = True auth = None if self.app.conf.get("NAVET_API_VERIFY_SSL", None) == 'false': verify_ssl = False if self.app.conf.get("NAVET_API_USER", None) and self.app.conf.get("NAVET_API_PW"): auth = (self.app.conf.get("NAVET_API_USER"), self.app.conf.get("NAVET_API_PW")) self._navet_api = Hammock(self.NAVET_API_URI, auth=auth, verify=verify_ssl) return self._navet_api
def ekopost_api(self): if self._ekopost_api is None: verify_ssl = True auth = None if self.app.config.get("EKOPOST_API_VERIFY_SSL", None) == 'false': verify_ssl = False if self.app.config.get( "EKOPOST_API_USER", None) and self.app.config.get("EKOPOST_API_PW"): auth = (self.app.config.get("EKOPOST_API_USER"), self.app.config.get("EKOPOST_API_PW")) self._ekopost_api = Hammock(self.app.config.get("EKOPOST_API_URI"), auth=auth, verify=verify_ssl) return self._ekopost_api
def __init__(self, username, password, host='https://api.cloudinsight.alertlogic.com', version='v1'): # We'll do our auth here so we have a working cloud insight hammock object pre_auth_ci = Hammock(host, auth=(username, password)) resp = pre_auth_ci.aims(version).authenticate.POST() logging.debug(resp.status_code) resp.raise_for_status() resp = resp.json() self.account_id = resp['authentication']['account']['id'] self.auth_token = resp['authentication']['token'] self.version = version headers = { 'x-aims-auth-token': self.auth_token, 'Accept-encoding': 'gzip' } self.ci = Hammock(host, headers=headers) self.tacoma = Tacoma(self) self.cloud_explorer = CloudExplorer(self) self.assets = Assets(self) self.aims = AIMS(self)
def test_urls(self): HTTPretty.register_uri(HTTPretty.GET, self.URL) client = Hammock(self.BASE_URL) combs = [ client.sample.path.to.resource, client('sample').path('to').resource, client('sample', 'path', 'to', 'resource'), client('sample')('path')('to')('resource'), client.sample('path')('to', 'resource'), client( 'sample', 'path', ).to.resource ] for comb in combs: self.assertEqual(str(comb), self.URL) resp = comb.GET() self.assertEqual(HTTPretty.last_request.path, self.PATH)
def __init__(self, rancher_base_url, access_key, secret_key, use_account_api=False, project_id=None): super(APIEndpoint, self).__init__() self.rancher_base_url = rancher_base_url self.access_key = access_key self.secret_key = secret_key self.use_account_api = use_account_api self.endpoint = Hammock(rancher_base_url) # endpoint starts from base/v2-beta self.endpoint = self.endpoint('v2-beta') # if it is an Account API access, you should provide project_id if use_account_api: if not project_id: raise Exception('missing project_id') self.endpoint = self.endpoint.projects(project_id)
def test_session(self): ACCEPT_HEADER = 'application/json' kwargs = { 'headers': { 'Accept': ACCEPT_HEADER }, 'auth': ('foo', 'bar'), } client = Hammock(self.BASE_URL, **kwargs) HTTPretty.register_uri(HTTPretty.GET, self.URL) client.sample.path.to.resource.GET() request = HTTPretty.last_request self.assertIn('User-Agent', request.headers) self.assertIn('Authorization', request.headers) self.assertIn('Accept', request.headers) self.assertEqual(request.headers.get('Accept'), ACCEPT_HEADER) client.sample.path.to.resource.GET() request = HTTPretty.last_request self.assertIn('User-Agent', request.headers) self.assertIn('Authorization', request.headers) self.assertIn('Accept', request.headers) self.assertEqual(request.headers.get('Accept'), ACCEPT_HEADER)
def __init__(self, username_or_access_token, password=None, device_ids=None, api_prefix='https://api.particle.io/v1', **kwargs): """ :param username_or_access_token: if access token, then no password is required :param password: :param device_ids: list of device ids to consider. only these devices will be part of the dynamic API if None, then all device ids are pulled from Particle Cloud :param api_prefix: base url of API server, defaults to https://api.particle.io/v1 :param **kwargs: hammock session will be initiated with passed kwargs. So if you like to use an http proxy pass your proxies dictionary here """ self.particle_cloud_api = Hammock(api_prefix + "/devices", **kwargs) self.api_prefix = api_prefix if password is None: self.access_token = username_or_access_token else: self.access_token = self._login(username_or_access_token, password) self.device_ids = device_ids self._get_devices()
def __init__(self): self.base_rest = Hammock(INASAFE_REALTIME_REST_URL, append_slash=True) self.session_login()
def test_append_slash_option(self): HTTPretty.register_uri(HTTPretty.GET, self.URL + '/') client = Hammock(self.BASE_URL, append_slash=True) resp = client.sample.path.to.resource.GET() self.assertEqual(HTTPretty.last_request.path, self.PATH + '/')
import pyglet import numpy as np from hammock import Hammock i = 1 hammock = Hammock(upper_length=4, slack=1) window = pyglet.window.Window() @window.event def on_mouse_press(x, y, button, modifiers): redraw(window, hammock) def redraw(window, hammock): print("Redraw") window.clear() hammock.slack = hammock.slack + 0.1 print(f"Slack {hammock.slack}") hammock.draw() hammock.print_results() pyglet.app.run()
def on_resize(self, width, height): """Position and size video image.""" super(GUI, self).on_resize(width, height) self.slack_slider.width = width - self.GUI_PADDING * 2 self.beta_slider.width = width - self.GUI_PADDING * 2 height -= self.GUI_HEIGHT if height <= 0: return drawing_width, drawing_height = 400, 400 if drawing_height == 0 or drawing_height == 0: return display_aspect = width / float(height) drawing_aspect = drawing_width / float(drawing_height) if drawing_aspect > display_aspect: self.drawing_width = width self.drawing_height = width / drawing_aspect else: self.drawing_height = height self.drawing_width = height * drawing_aspect self.drawing_x = (width - self.drawing_width) / 2 self.drawing_y = (height - self.drawing_height) / 2 + self.GUI_HEIGHT if __name__ == "__main__": hammock = Hammock() gui = GUI(hammock) gui.set_visible(True) pyglet.app.run()
def poll_func(self): try: variables = self.hammock_instance.GET( verify=False).json()["variables"] for key in variables.keys(): self.setValue(key, variables[key]) except Exception: print("error getting variables for RemoteRestResource {}".format( self.name)) exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) traceback.print_exception( exc_type, exc_value, exc_traceback, limit=7, file=sys.stdout) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--debug', dest="debug", help="turn on debugging.", action='store_true') parser.add_argument('address', help="address of server", nargs="?", default="127.0.0.1") parser.add_argument('port', help="port of server", nargs="?", default=9003) args = parser.parse_args() client = RemoteRestResource("Greenhouse", Hammock( "https://tripzero.reesfamily12.com:8069/DeviceManager/DeviceManager")) print("client variables: {}".format(client.variables))
raise Exception( "No driver specified in config or arguments (--driver)") driver = Driver(debug=args.debug) if args.device_name: import spyrk key = config['particleKey'] s = spyrk.SparkCloud(key) if "particleApiServer" in config.keys(): apiServer = config["particleApiServer"] from hammock import Hammock s = spyrk.SparkCloud(key, spark_api=Hammock(apiServer)) print("trying to get ip address and numLights from particle server...") args.address = s.devices[args.device_name].ip args.numLeds = s.devices[args.device_name].numLights print(args.address) if driver_name == "LightProtocol" or driver_name == "LightClientWss": driver.connectTo(args.address, args.port, useSsl=False) leds = photons.LightArray2(args.numLeds, driver, fps=args.fps) leds.clear() if args.rainbow:
import json import pathlib import pickle import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates from hammock import Hammock redcap = Hammock('https://redcap.ahc.umn.edu/api/') config = { "redcap_fitbit_key": "enrollment key here", "redcap_fitbit_survey_key": "ema key here" } def num(s): try: return float(s) except ValueError: return 0.0 def get_stressors(subject_id): q_r = redcap.POST( data={ 'token': config['redcap_fitbit_key'], 'content': 'record', 'instrument': 'eligibility', 'type': 'flat', 'format': 'json',
def setUp(self): self.inasafe_django = Hammock(INASAFE_REALTIME_REST_URL)
def __init__(self): self.root = Hammock(self.API_ROOT)