def test_unauthorized_access(self):
     """
     1. Try access to permissions controllers with wrong api key
     """
     api = AuthService(self.API_URL, auth=(self.application.id, 'wrong-secret-token'), append_slash=True)
     self.assertEqual(401, api.permissions.GET().status_code)
     self.assertEqual(401, api.permissions(self.permission.id).GET().status_code)
     self.assertEqual(401, api.users(self.user.id).permissions.POST(data=dict(code=self.permission.code)).status_code)
     self.assertEqual(401, api.users(self.user.id).permissions(self.permission.code).DELETE().status_code)
Example #2
0
 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 get_signature_count(api_key,petition_id):
    changeorg = ChangeOrg('https://api.change.org/v1')

    params = {
        'api_key': api_key,
    } 

    petitions = changeorg.petitions(petition_id).signatures.GET(params=params).json
    signature_count = petitions.get('signature_count')

    return signature_count
Example #4
0
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
Example #5
0
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
Example #6
0
 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)
Example #7
0
    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
Example #8
0
class Politifact():
    API_ROOT = 'http://www.politifact.com/api'
    EDITION = 'truth-o-meter'

    def __init__(self):
        self.root = Hammock(self.API_ROOT)

    def statements(self):
        return StatementsEndpoint(self.root)

    def promises(self):
        return PromisesEndpoint(self.API_ROOT)

    def stories(self, n=None):
        full_endpoint = self.root.stories().json()
        if n:
            full_endpoint += '?n={}'.format(n)
        return full_endpoint.GET()

    def updates(self):
        return UpdatesEndpoint(self.API_ROOT)

    def subjects(self):
        return SubjectsEndpoint(self)

    def people(self):
        return PeopleEndpoint(self)

    def rulings(self):
        return RulingsEndpoint(self)
Example #9
0
 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))
Example #10
0
 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)
Example #11
0
    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)
Example #12
0
 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)
Example #13
0
    def test_urls_ignore(self):
        client = Hammock(BASE_URL, ignore=(False, None))
        combs = [
            client.sample(False).path.to(None).resource,
            client('sample', False).path('to', None).resource,
            client('sample', False, 'path', 'to', None, 'resource'),
            client('sample')(False)('path')('to')(None)('resource'),
            client.sample(False, 'path')('to', None, 'resource'),
            client('sample', False, 'path',).to(None).resource
        ]

        for comb in combs:
            self.assertEqual(str(comb), URL)
            resp = comb.GET()
            self.assertIsNotNone(resp.json)
            self.assertIsNotNone(resp.json.get('path', None))
            self.assertEqual(resp.json.get('path'), PATH)
Example #14
0
    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 test_wrong_content_type(self):
     """
     1. Try make request with wrong data encoding
     """
     # Step 1
     self.api = AuthService(self.API_URL, auth=(self.application.id, 'secret-token'), append_slash=True, headers={
         'content-type': 'wrong-content-type'
     })
     response = self.api.users(self.user.id).permissions.POST(data=dict(code=self.permission.code))
     self.assertEqual(400, response.status_code)
    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)
Example #17
0
    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)
Example #18
0
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
Example #19
0
def main():
    args = get_args()

    log_level = getattr(logging, args.log.upper())
    logging.basicConfig(level=log_level)

    github = Hammock('https://api.github.com')
    user = github.users(args.username)

    base_dir = args.dir
    clone_actions = [partial(repo.mirror, base_dir)
                        for repo in get_repos_and_gists(user)]

    logging.info("About to clone %d repos for user '%s'.",
                 len(clone_actions), args.username)

    do_multiple(4, clone_actions)

    logging.info("Done to cloning %d repos for user '%s'.",
                 len(clone_actions), args.username)
class APIEndpoint(object):

    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)

    @property
    def auth_param(self):
        return self.access_key, self.secret_key

    @property
    def request_contexts(self):
        return {
            'auth': self.auth_param
        }

    def stacks(self, stack_id):
        response = self.endpoint.stacks(stack_id).GET(**self.request_contexts)
        obj = response.json()
        return StackResource(self, obj)

    def services(self, service_id):
        response = self.endpoint.services(service_id).GET(**self.request_contexts)
        obj = response.json()
        return ServiceResource(self, obj)
Example #21
0
 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
Example #22
0
    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()
Example #23
0
 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 test_application_permissions(self):
        """
        1. Create one more application
        2. Access to application permissions with first app
        3. Access to application permissions with second app
        4. Access to application permission details
        """
        # Step 1
        second_application = CampusApplication.objects.create(title='Student service', access_token='secret-token')
        second_permission = CampusPermission.objects.create(application=second_application, code='add-student',
                                                            title='Add student',
                                                            description='Indicate can user add students or not')
        CampusPermission.objects.create(application=second_application, code='edit-student', title='Edit student')

        # Step 2
        first_app_api = AuthService(self.API_URL, auth=(self.application.id, 'secret-token'), append_slash=True)
        response = first_app_api.permissions.GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, response.json().get('meta').get('total_count'))
        self.assertEqual('add-entrant', response.json().get('objects')[0]['code'])

        # Step 3
        second_app_api = AuthService(self.API_URL, auth=(second_application.id, 'secret-token'), append_slash=True)
        response = second_app_api.permissions.GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, response.json().get('meta').get('total_count'))
        self.assertSetEqual(
            {'add-student', 'edit-student'},
            {response.json().get('objects')[0]['code'], response.json().get('objects')[1]['code']}
        )

        # Step 4
        response = second_app_api.permissions(second_permission.code).GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual(second_permission.title, response.json()['title'])
        self.assertEqual(second_permission.description, response.json()['description'])
        self.assertEqual(second_permission.code, response.json()['code'])
Example #25
0
 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
Example #26
0
    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)
Example #27
0
    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()
Example #28
0
    def __init__(self):
        Resource.__init__(self, "SolarPower", [
            "current_power", "available_power", "energy_day", "energy_month",
            "energy_lifetime", "energy_year"
        ])

        self.solar_edge = SolarEdge('https://monitoringapi.solaredge.com')

        config_rsrc = get_resource("ConfigurationResource")

        self.api_key = config_rsrc.get_value("solaredge_api")
        self.format = 'application/json'

        self.id = self._get_id()

        self.poller = resource_poll(self.poll_func, MINS(5), is_coroutine=True)
Example #29
0
 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)
Example #30
0
 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 + '/')
 def setUp(self):
     self.application = CampusApplication.objects.create(title='Entrant service', access_token='secret-token')
     self.api = AuthService(self.API_URL, auth=(self.application.id, 'secret-token'), append_slash=True)
     self.user = CampusUser.objects.create_user('*****@*****.**', 'pass')
     self.permission = CampusPermission.objects.create(application=self.application, code='add-entrant', title='Add entrant')
Example #32
0
from hammock import Hammock as Github
import json
import urllib
import sys
import base64
import filecmp

from pprint import pprint

github = Github('https://api.github.com')
owner = 'maddyloo'
repo = 'BibProject'
user = '******'
password = '******' #Github token goes here

filename = "Aitken, Alexander C..tex"
encoded_filename=urllib.quote(filename)
path = 'tex_files/'+encoded_filename

data={'ref':"changes"}

## Step ONE: get the current file so we can extract its hash
## this isn't the "canonical" way to go about making a commit
## described variously with five or seven steps:
##    http://www.mdswanson.com/blog/2011/07/23/digging-around-the-github-api-take-2.html
##    http://stackoverflow.com/a/14672793/821010
## but this is a cheap and dirty method that will work without hassle.
## and the "proper" way to go about it can be investigated separately.
resp = github.repos(owner, repo).contents(path).GET(
    	auth = (user, password),
        headers = {'Content-type': 'application/json'},
Example #33
0
class ParticleCloud(object):
    """
    Provides access to the Particle cloud to call function, read variables,
    subscribe for events and publish events.
    """

    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()

    @staticmethod
    def wait_forever(self):
        while True:
            try:
                time.sleep(3600)
            except:
                continue

    @staticmethod
    def _check_error(response):
        """Raises an exception if the Particle Cloud returned an error."""
        if (not response.ok) or (response.status_code != 200):
            raise Exception(
                response.json()['error'] + ': ' +
                response.json()['error_description']
            )

    def _login(self, username, password):
        data = {
            'username': username,
            'password': password,
            'grant_type': 'password'
        }

        # https://docs.particle.io/reference/api/
        # You must give a valid client ID and password in HTTP Basic Auth.
        # For controlling your own developer account, you can use particle:particle.
        res = self.particle_cloud_api.oauth.token.POST(auth=('particle', 'particle'), data=data)
        self._check_error(res)
        return res.json()['access_token']

    def _get_devices(self):
        """Create a dictionary of devices known to the user account."""
        params = {'access_token': self.access_token}
        res = self.particle_cloud_api.GET(params=params)
        self._check_error(res)
        json_list = res.json()

        self.devices = {}
        if json_list:
            for d in json_list:
                if self.device_ids is None or (self.device_ids is not None and d['id'] in self.device_ids):
                    info = self._get_device_info(d['id'])
                    d['functions'] = info['functions']
                    d['variables'] = info['variables']
                    d['device_id'] = d['id']  # my preference is to call it device_id
                    d['particle_device_api'] = self.particle_cloud_api(d['id'])
                    d['access_token'] = self.access_token
                    d['api_prefix'] = self.api_prefix

                    self.devices[d['name']] = _ParticleDevice(**d)

    def _get_device_info(self, device_id):
        """
            Queries the Particle Cloud for detailed information about a device.
        """
        params = {'access_token': self.access_token}
        r = self.particle_cloud_api(device_id).GET(params=params)
        self._check_error(r)
        return r.json()

    def __getattr__(self, name):
        """
            Returns a Device object as an attribute of the ParticleCloud object.

            accessed like:
            particle_cloud_variable.device_name

        """
        if name in self.devices:
            return self.devices[name]
        else:
            raise AttributeError()
Example #34
0
    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()
Example #35
0
from hammock import Hammock as Github
import json
import urllib
import sys
import base64
import filecmp

from pprint import pprint

github = Github('https://api.github.com')
owner = 'maddyloo'
repo = 'BibProject'
user = '******'
password = '******' #Github token goes here

filename = "Aitken, Alexander C..tex"

data = {"title": "Update to " + filename,
        "body": "Please pull this in!",
        "head": "changes",
        "base": "master"}

resp = github.repos(owner, repo).pulls.POST(
    	auth = (user, password),
        headers = {'Content-type': 'application/json'},
        data=json.dumps(data))

pprint(resp._content)
Example #36
0
		if __name__ == "__main__":
			reload(sys)
			sys.setdefaultencoding("utf-8")
		#write each headline to new line	
		file.write(span.string + "\n")

file.close()

#upload file to github

with open( filename, "rb") as text_file:
	encoded_string = base64.b64encode(text_file.read())

data = {'message':'Adding "'+filename+'".',
      'committer':{'name':'Madeleine Corneli',
                   'email':'*****@*****.**'},
      'content':encoded_string,
      'branch':'master'}

github = Github('https://api.github.com')
user = '******'
password = raw_input("Github password:")
repo = 'miniBibServer'
resp = github.repos(user, repo).contents(filename).PUT(
	auth = (user, password),
	headers = {'Content-type': 'textfile'},
	data = json.dumps(data))

pprint (vars(resp))

#edit to test git :/
Example #37
0
from hammock import Hammock as Github
import json
import urllib
import sys
import base64
import filecmp

from pprint import pprint

github = Github('https://api.github.com')
owner = 'maddyloo'
repo = 'BibProject'
user = '******'
password = '******'  #Github token goes here

filename = "Aitken, Alexander C..tex"
encoded_filename = urllib.quote(filename)
path = 'tex_files/' + encoded_filename

data = {'ref': "changes"}

## Step ONE: get the current file so we can extract its hash
## this isn't the "canonical" way to go about making a commit
## described variously with five or seven steps:
##    http://www.mdswanson.com/blog/2011/07/23/digging-around-the-github-api-take-2.html
##    http://stackoverflow.com/a/14672793/821010
## but this is a cheap and dirty method that will work without hassle.
## and the "proper" way to go about it can be investigated separately.
resp = github.repos(owner, repo).contents(path).GET(
    auth=(user, password),
    headers={'Content-type': 'application/json'},
 def __init__(self):
     self.base_rest = Hammock(INASAFE_REALTIME_REST_URL, append_slash=True)
     self.session_login()
file.close()

#upload file to github

with open(filename, "rb") as text_file:
    encoded_string = base64.b64encode(text_file.read())

data = {
    'message': 'Adding "' + filename + '".',
    'committer': {
        'name': 'Madeleine Corneli',
        'email': '*****@*****.**'
    },
    'content': encoded_string,
    'branch': 'master'
}

github = Github('https://api.github.com')
user = '******'
password = raw_input("Github password:")
repo = 'miniBibServer'
resp = github.repos(user, repo).contents(filename).PUT(
    auth=(user, password),
    headers={'Content-type': 'textfile'},
    data=json.dumps(data))

pprint(vars(resp))

#edit to test git :/
class ExternalApiTest(LiveServerTestCase):
    API_URL = 'http://*****:*****@example.com', 'pass')
        self.permission = CampusPermission.objects.create(application=self.application, code='add-entrant', title='Add entrant')

    def test_grant_permission(self):
        """
        1. Check correct query
        2. Check query with missed code arg
        3. Check query with wrong permission code
        4. Grant permission to missed user
        """
        # Step 1
        response = self.api.users(self.user.id).permissions.POST(data=dict(code=self.permission.code))  # Api call
        self.assertEqual(201, response.status_code)
        self.assertEqual(1, CampusPermission.objects.for_user(self.user).count())
        self.assertEqual(self.permission.id, CampusPermission.objects.for_user(self.user)[0].id)

        # Step 2
        response = self.api.users(self.user.id).permissions.POST()  # Api call
        self.assertEqual(400, response.status_code)

        # Step 3
        response = self.api.users(self.user.id).permissions.POST(data=dict(code='wrong-permission-code'))  # Api call
        self.assertEqual(400, response.status_code)

        # Step 4
        response = self.api.users(666).permissions.POST(data=dict(code=self.permission.code))  # Api call
        self.assertEqual(404, response.status_code)

    def test_revoke_permission(self):
        self.permission.grant_to(self.user)
        response = self.api.users(self.user.id).permissions(self.permission.code).DELETE()  # Api call

        self.assertEqual(204, response.status_code)
        self.assertEqual(0, CampusPermission.objects.for_user(self.user).count())

    def test_check_permission(self):
        self.permission.grant_to(self.user)
        response = self.api.users(self.user.id).permissions(self.permission.code).GET()  # Api call
        self.assertEqual('add-entrant', response.json().get('code'))

        self.permission.revoke_for(self.user)
        response = self.api.users(self.user.id).permissions(self.permission.code).GET()  # Api call
        self.assertEqual(404, response.status_code)

    def test_list_permissions(self):
        self.permission.grant_to(self.user)
        response = self.api.users(self.user.id).permissions.GET()  # Api call
        self.assertEqual(1, response.json().get('meta').get('total_count'))

    def test_grand_and_revoke_for_common_permission(self):
        """
        1. Create second user
        2. Grant permission to both
        3. Revoke permissions from one user
        4. Check permissions for both users
        """
        # Step 1
        user_b = CampusUser.objects.create_user('*****@*****.**', 'pass')

        # Step 2
        self.api.users(self.user.id).permissions.POST(data=dict(code=self.permission.code))
        self.api.users(user_b.id).permissions.POST(data=dict(code=self.permission.code))

        # Step 3
        response = self.api.users(self.user.id).permissions(self.permission.code).DELETE()
        self.assertEqual(204, response.status_code)

        # Step 4
        response = self.api.users(self.user.id).permissions(self.permission.code).GET()
        self.assertEqual(404, response.status_code)

        response = self.api.users(user_b.id).permissions(self.permission.code).GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual('add-entrant', response.json().get('code'))

    def test_wrong_content_type(self):
        """
        1. Try make request with wrong data encoding
        """
        # Step 1
        self.api = AuthService(self.API_URL, auth=(self.application.id, 'secret-token'), append_slash=True, headers={
            'content-type': 'wrong-content-type'
        })
        response = self.api.users(self.user.id).permissions.POST(data=dict(code=self.permission.code))
        self.assertEqual(400, response.status_code)

    def test_application_permissions(self):
        """
        1. Create one more application
        2. Access to application permissions with first app
        3. Access to application permissions with second app
        4. Access to application permission details
        """
        # Step 1
        second_application = CampusApplication.objects.create(title='Student service', access_token='secret-token')
        second_permission = CampusPermission.objects.create(application=second_application, code='add-student',
                                                            title='Add student',
                                                            description='Indicate can user add students or not')
        CampusPermission.objects.create(application=second_application, code='edit-student', title='Edit student')

        # Step 2
        first_app_api = AuthService(self.API_URL, auth=(self.application.id, 'secret-token'), append_slash=True)
        response = first_app_api.permissions.GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual(1, response.json().get('meta').get('total_count'))
        self.assertEqual('add-entrant', response.json().get('objects')[0]['code'])

        # Step 3
        second_app_api = AuthService(self.API_URL, auth=(second_application.id, 'secret-token'), append_slash=True)
        response = second_app_api.permissions.GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual(2, response.json().get('meta').get('total_count'))
        self.assertSetEqual(
            {'add-student', 'edit-student'},
            {response.json().get('objects')[0]['code'], response.json().get('objects')[1]['code']}
        )

        # Step 4
        response = second_app_api.permissions(second_permission.code).GET()
        self.assertEqual(200, response.status_code)
        self.assertEqual(second_permission.title, response.json()['title'])
        self.assertEqual(second_permission.description, response.json()['description'])
        self.assertEqual(second_permission.code, response.json()['code'])

    def test_unauthorized_access(self):
        """
        1. Try access to permissions controllers with wrong api key
        """
        api = AuthService(self.API_URL, auth=(self.application.id, 'wrong-secret-token'), append_slash=True)
        self.assertEqual(401, api.permissions.GET().status_code)
        self.assertEqual(401, api.permissions(self.permission.id).GET().status_code)
        self.assertEqual(401, api.users(self.user.id).permissions.POST(data=dict(code=self.permission.code)).status_code)
        self.assertEqual(401, api.users(self.user.id).permissions(self.permission.code).DELETE().status_code)
Example #41
0
import os
import time
from threading import Thread

import feedparser

from hammock import Hammock as BeeminderAPI

BEEMINDER_API_URL = os.environ.get('BEEMINDER_API_URL')
USERNAME = os.environ.get('USERNAME')
AUTH_TOKEN = os.environ.get('AUTH_TOKEN')
GOAL = os.environ.get('GOAL')
FEED_URL = os.environ.get('FEED_URL')


beeminder = BeeminderAPI(BEEMINDER_API_URL)
datapoints = beeminder.users(USERNAME).goals(GOAL, 'datapoints.json')


def get_beeminder_links():
    print("Getting Beeminder links...")
    existing_datapoints = datapoints.GET(params={"auth_token": AUTH_TOKEN}).json()
    beeminder_links = set(point['comment'] for point in existing_datapoints)
    return beeminder_links


def get_feed_links():
    print("Getting feed links...")
    feed = feedparser.parse(FEED_URL)['entries']
    feed_links = set(entry['link'] for entry in feed)
    return feed_links
Example #42
0
from hammock import Hammock as Github
import json
import base64
from pprint import pprint

# Let's create the first chain of hammock using base api url
github = Github('https://api.github.com')

user = '******'
# In the future this will be running on a server
# somewhere, so password can just be hard coded
password = raw_input("Enter your github password: ")
repo = 'py-blot'

# The most interesting things for us are in this part of the API
# https://developer.github.com/v3/repos/contents/

# get the contents of a given file, the README in this case
resp = github.repos(user, repo).contents.GET('README.md')

# examine the file we retrieved,
# here's how to have a look at everything:
#pprint(vars(resp))
# And from that, the most interesting part(s) can be extracted:
text = base64.b64decode(json.loads(resp._content)['content'])
# (we will need the sha later)
sha = json.loads(resp._content)['sha']

print text

# Now to further explore the API, let's loop back and
from hammock import Hammock as Github
import json
import urllib
import sys
import base64
from pprint import pprint

github = Github('https://api.github.com')
owner = 'maddyloo'
repo = 'BibProject'
path = 'tex_files/Aitken%2C%20Alexander%20C..tex'
password = ''  #BibPoject token
#Aitken%2C Alexander C..tex

#GET /repos/:owner/:repo/contents/:path
resp = github.repos(owner, repo).contents(path).GET(
	auth = (owner, password),
	headers = {'Content-type': 'textfile'})
	#data = json.dumps(data))

#j = json.loads(resp.text)
j = resp.json()
print(base64.b64decode(j['content']))
#pprint(resp.content)
# -*- coding: utf-8; -*-

from hammock import Hammock as Github
import json
import urllib
import sys
import base64
import filecmp

from pprint import pprint

github = Github('https://api.github.com')
owner = 'maddyloo'
repo = 'BibProject'
user = '******'
password = '******' #Github token goes here

filename = "Aitken, Alexander C..tex"
# Maps to AitkenAlexanderC as a "canonical name"
basename = re.sub('[ ,.]', '', filename.split(".")[0])

## Step ZERO: get a reference
resp = github.repos(owner, repo).git.refs('heads/master').GET(
    	auth = (user, password))
sha_latest_commit = json.loads(resp._content)['object']['sha']

## Step ONE: create the branch derived from that reference
data={"ref": "refs/heads/"+basename,
      "sha": sha_latest_commit}

resp = github.repos(owner, repo).git.refs.POST(
Example #45
0
 def setUp(self):
     self.inasafe_django = Hammock(INASAFE_REALTIME_REST_URL)
Example #46
0
    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))