Esempio n. 1
0
class ContextIO(object):
    url_base = "https://api.context.io"

    def __init__(self, consumer_key, consumer_secret):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self, uri, method="GET", params={}, headers={}):
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers)
        status = int(response['status'])

        if status >= 200 and status < 300:
            body = json.loads(body)
            return body

        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers):
        body = ''
        if method == 'GET' and params:
            url += '?' + urlencode(params)
        elif method == 'POST' and params:
            body = urlencode(params)
        print method + ' ' + url        
        return self.client.request(url, method, headers=headers, body=body)

    def get_accounts(self, **params):
        params = Resource.sanitize_params(params, ['email', 'status', 'status_ok', 'limit', 'offset'])
        return [Account(self, obj) for obj in self.request_uri('accounts', params=params)]

    def post_account(self, email, **params):
        params = Resource.sanitize_params(params, ['first_name', 'last_name'])
        params['email'] = email
        return Account(self, self.request_uri('accounts', method="POST", params=params))

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def handle_request_error(self, response, body):
        try:
            import logging        	
            logging.info('body '+str(body))	
            body = json.loads(body)
            raise Exception('HTTP %(status)s - %(type)s %(code)s: %(message)s' % { 'status': response['status'], 'type': body['type'], 'code': body['code'], 'message': body['value']})
        except ValueError:
            raise Exception('HTTP %(status)s: %(body)s' % {'status':response['status'], 'body':body})
Esempio n. 2
0
class ContextIO(object):
    url_base = "https://api-preview.context.io"

    def __init__(self, consumer_key, consumer_secret):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self, uri, method="GET", params={}, headers={}):
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers)
        status = int(response['status'])

        if status == 200:
            body = json.loads(body)
            return body

        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers):
        if params:
            url += '?' + urlencode(params)

        print "{method} {url}".format(url=url, method=method)
        return self.client.request(url, method, headers=headers)

    def get_accounts(self):
        return [Account(self, obj) for obj in self.request_uri('accounts')]

    def post_account(self, email, first_name=None, last_name=None):
        pass

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def handle_request_error(self, response, body):
        messages = []
        try:
            body = json.loads(body)
            for message in body['messages']:
                if message['type'] == 'error':
                    messages.append("error {0}".format(message['code']))
            raise Exception('HTTP {status}: {message}'.format(status=response['status'], message=', '.join(messages)))

        except ValueError:
            raise Exception('HTTP {status}: {body}'.format(status=response['status'], body=body))
Esempio n. 3
0
class ContextIO(object):
    url_base = "https://api.context.io"

    def __init__(self, consumer_key, consumer_secret):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self, uri, method="GET", params={}, headers={}):
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers)
        status = int(response['status'])

        if status in (200, 201) :
            body = json.loads(body)
            return body

        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers):
        query_params = urlencode(params)
        if params and method == 'GET':
            url += '?' + query_params
            return self.client.request(url, method, headers=headers)
        return self.client.request(url, method, query_params, headers=headers)
        
    def get_accounts(self):
        return [Account(self, obj) for obj in self.request_uri('accounts')]

    def post_account(self, email, first_name=None, last_name=None):
        pass

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def handle_request_error(self, response, body):
        messages = []
        try:
            body = json.loads(body)
            raise Exception('HTTP {status}: {message}'.format(status=response['status'], message=body['value']))

        except ValueError:
            raise Exception('HTTP {status}: {body}'.format(status=response['status'], body=body))
Esempio n. 4
0
class ContextIO(object):
    url_base = "https://api.context.io"

    def __init__(self, consumer_key, consumer_secret, timeout=None):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer, timeout=timeout)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self,
                    uri,
                    method="GET",
                    params=None,
                    headers=None,
                    data={}):
        if params is None:
            params = {}
        if headers is None:
            headers = {}
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers, data=data)
        status = int(response['status'])

        if status >= 200 and status < 300:
            # file content doesn't return json
            if re.match(r'accounts/\w+/files/\w+/content', uri):
                return body
            # message source doesn't return json
            if re.match(r'accounts/\w+/messages/\w+/source', uri):
                return body
            body = json.loads(body)
            return body
        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers, data=''):
        body = ''
        if method == 'GET' and params:
            url += '?' + urlencode(params)
        elif method == 'POST' and params:
            body = urlencode(params, doseq=True)
        if data:
            body = json.dumps(data)
        print method + ' ' + url
        return self.client.request(url, method, headers=headers, body=body)

    def get_accounts(self, **params):
        params = Resource.sanitize_params(
            params, ['email', 'status', 'status_ok', 'limit', 'offset'])
        return [
            Account(self, obj)
            for obj in self.request_uri('accounts', params=params)
        ]

    def get_account(self, account_id):
        return Account(self, self.request_uri('accounts/%s' % account_id))

    def post_account(self, email, **params):
        params = Resource.sanitize_params(params, ['first_name', 'last_name'])
        params['email'] = email
        return Account(
            self, self.request_uri('accounts', method="POST", params=params))

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def get_connect_tokens(self):
        return [
            ConnectToken(self, obj)
            for obj in self.request_uri('connect_tokens')
        ]

    def get_connect_token(self, token):
        obj = self.request_uri('connect_tokens/%s' % token)
        return ConnectToken(self, obj)

    def post_connect_token(self, callback_url, **params):
        params = Resource.sanitize_params(params, [
            'service_level', 'email', 'first_name', 'last_name',
            'source_callback_url', 'source_sync_flags', 'source_raw_file_list'
        ])
        params['callback_url'] = callback_url
        resp = self.request_uri('connect_tokens', method='POST', params=params)
        token = resp['token']
        redirect_url = resp['browser_redirect_url']
        return (token, redirect_url)

    def handle_request_error(self, response, body):
        status_code = int(response['status'])
        try:
            body = json.loads(body)
            raise RequestError(
                status_code,
                'HTTP %(status)s - %(type)s %(code)s: %(message)s' % {
                    'status': response['status'],
                    'type': body['type'],
                    'code': body['code'],
                    'message': body['value']
                })
        except (ValueError, TypeError, KeyError):
            raise RequestError(
                status_code, 'HTTP %(status)s: %(body)s' % {
                    'status': response['status'],
                    'body': body
                })
Esempio n. 5
0
class ContextIO(object):
    url_base = "https://api.context.io"

    def __init__(self, consumer_key, consumer_secret):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self, uri, method="GET", params={}, headers={}):
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers)
        status = int(response['status'])

        if status >= 200 and status < 300:
            body = json.loads(body)
            return body

        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers):
        body = ''
        if method == 'GET' and params:
            url += '?' + urlencode(params)
        elif method == 'POST' and params:
            body = urlencode(params)
        print method + ' ' + url
        return self.client.request(url, method, headers=headers, body=body)

    def get_accounts(self, **params):
        params = Resource.sanitize_params(
            params, ['email', 'status', 'status_ok', 'limit', 'offset'])
        return [
            Account(self, obj)
            for obj in self.request_uri('accounts', params=params)
        ]

    def post_account(self, email, **params):
        params = Resource.sanitize_params(params, ['first_name', 'last_name'])
        params['email'] = email
        return Account(
            self, self.request_uri('accounts', method="POST", params=params))

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def handle_request_error(self, response, body):
        try:
            body = json.loads(body)
            raise Exception(
                'HTTP %(status)s - %(type)s %(code)s: %(message)s' % {
                    'status': response['status'],
                    'type': body['type'],
                    'code': body['code'],
                    'message': body['value']
                })
        except ValueError:
            raise Exception('HTTP %(status)s: %(body)s' % {
                'status': response['status'],
                'body': body
            })
Esempio n. 6
0
class ContextIO(object):
    url_base = "https://api.context.io"

    def __init__(self, consumer_key, consumer_secret, timeout=None):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer, timeout=timeout)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self, uri, method="GET", params=None, headers=None, data={}):
        if params is None:
            params = {}
        if headers is None:
            headers = {}
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers, data=data)
        status = int(response['status'])

        if status >= 200 and status < 300:
            # file content doesn't return json
            if re.match(r'accounts/\w+/files/\w+/content', uri):
                return body
            # message source doesn't return json
            if re.match(r'accounts/\w+/messages/\w+/source', uri):
                return body
            body = json.loads(body)
            return body
        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers, data=''):
        body = ''
        if method == 'GET' and params:
            url += '?' + urlencode(params)
        elif method == 'POST' and params:
            body = urlencode(params, doseq=True)
        if data:
            body = json.dumps(data)
        print method + ' ' + url
        return self.client.request(url, method, headers=headers, body=body)

    def get_accounts(self, **params):
        params = Resource.sanitize_params(params, ['email', 'status', 'status_ok', 'limit', 'offset'])
        return [Account(self, obj) for obj in self.request_uri('accounts', params=params)]

    def get_account(self, account_id):
        return Account(self, self.request_uri('accounts/%s' % account_id))

    def post_account(self, email, **params):
        params = Resource.sanitize_params(params, ['first_name', 'last_name'])
        params['email'] = email
        return Account(self, self.request_uri('accounts', method="POST", params=params))

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def get_connect_tokens(self):
        return [ConnectToken(self, obj) for obj in self.request_uri('connect_tokens')]

    def get_connect_token(self, token):
        obj = self.request_uri('connect_tokens/%s' % token)
        return ConnectToken(self, obj)

    def post_connect_token(self, callback_url, **params):
        params = Resource.sanitize_params(params, ['service_level', 'email', 'first_name', 'last_name',
                                                   'source_callback_url', 'source_sync_flags', 'source_raw_file_list'])
        params['callback_url'] = callback_url
        resp = self.request_uri('connect_tokens', method='POST', params=params)
        token = resp['token']
        redirect_url = resp['browser_redirect_url']
        return (token, redirect_url)

    def handle_request_error(self, response, body):
        status_code = int(response['status'])
        try:
            body = json.loads(body)
            raise RequestError(status_code, 'HTTP %(status)s - %(type)s %(code)s: %(message)s' % { 'status': response['status'], 'type': body['type'], 'code': body['code'], 'message': body['value']})
        except (ValueError, TypeError, KeyError):
            raise RequestError(status_code, 'HTTP %(status)s: %(body)s' % {'status':response['status'], 'body':body})
Esempio n. 7
0
class ContextIO(object):
    url_base = "https://api.context.io"

    def __init__(self, consumer_key, consumer_secret):
        self.consumer = Consumer(key=consumer_key, secret=consumer_secret)
        self.client = Client(self.consumer)
        self.client.set_signature_method(sha1())
        self.base_uri = '2.0'

    def request_uri(self, uri, method="GET", params={}, headers={}):
        url = '/'.join((self.url_base, self.base_uri, uri))
        response, body = self.request(url, method, params, headers)
        status = int(response['status'])

        if (status >= 200 and status < 300) or (status >= 400):
            body = json.loads(body)
            return body

        else:
            self.handle_request_error(response, body)

    def request(self, url, method, params, headers):
        body = ''
        if method == 'GET' and params:
            url += '?' + urlencode(params)
        elif method == 'POST' and params:
            body = urlencode(params)
        #print "{method} {url}".format(url=url, method=method)
        return self.client.request(url, method, headers=headers, body=body)

    def get_accounts(self, **params):
        params = Resource.sanitize_params(params, ['email', 'status', 'status_ok', 'limit', 'offset'])
        return [Account(self, obj) for obj in self.request_uri('accounts', params=params)]

    def post_account(self, email, **params):
        params = Resource.sanitize_params(params, ['first_name', 'last_name'])
        params['email'] = email
        return Account(self, self.request_uri('accounts', method="POST", params=params))

    def delete_account(self, account_id):
        pass

    def put_account(self, first_name=None, last_name=None):
        pass

    def get_connect_tokens(self):
        return [ConnectToken(self, obj) for obj in self.request_uri('connect_tokens')]

    # Zhe Yang
    def get_account_connect_tokens(self, account_id):
        return [ConnectToken(self, obj) for obj in self.request_uri('accounts/%s/connect_tokens' % account_id)]

    # Zhe Yang
    def post_account_connect_token(self, account_id, callback_url, **params):
        params = Resource.sanitize_params(params, ['service_level', 'email', 'first_name', 'last_name', 'source_callback_url', 'source_sync_flags', 'source_raw_file_list'])
        params['callback_url'] = callback_url
        resp = self.request_uri('accounts/%s/connect_tokens' % account_id, method='POST', params=params)
        token = resp['token']
        redirect_url = resp['browser_redirect_url']
        return (token, redirect_url)

    def get_connect_token(self, token):
        obj = self.request_uri('connect_tokens/%s' % token)
        return ConnectToken(self, obj)

    def post_connect_token(self, callback_url, **params):
        params = Resource.sanitize_params(params, ['service_level', 'email', 'first_name', 'last_name', 'source_callback_url', 'source_sync_flags', 'source_raw_file_list'])
        params['callback_url'] = callback_url
        resp = self.request_uri('connect_tokens', method='POST', params=params)
        token = resp['token']
        redirect_url = resp['browser_redirect_url']
        return (token, redirect_url)

    def handle_request_error(self, response, body):
        messages = []
        try:
            body = json.loads(body)
            for message in body['messages']:
                if message['type'] == 'error':
                    messages.append("error {0}".format(message['code']))
            raise Exception('HTTP {status}: {message}'.format(status=response['status'], message=', '.join(messages)))

        except (ValueError, KeyError):
            raise Exception('HTTP {status}: {body}'.format(status=response['status'], body=body))