コード例 #1
0
 def query_rsr_for_org(url_template, url_args, token, field_name='id'):
     """
     wrapper around Requester for a number of similar requests to try find an organisation
     """
     try:
         request = Requester(
             url_template=url_template,
             url_args=url_args,
             headers={
                 'Content-type': 'application/json',
                 'Accept': 'application/json',
                 'Encoding': 'utf-8',
                 'Authorization': 'Token {}'.format(token)
             },
         )
         data = request.response.json()
         if data.get('count', 0) == 1:
             # return org ID and the content owner ID if available
             return data['results'][0][field_name], data['results'][0].get(
                 'content_owner', None)
         elif data.get('count', 0) == 0:
             return None, None
         else:
             raise Exception(
                 "Multiple matches when looking for organisation using {}".
                 format(url_template.format(**url_args)))
     except Exception, e:
         print "{message}".format(message=e.message)
         raise Exception("Requester error, message:\n{}".format(e.message))
コード例 #2
0
def api_user(domain, username, password='', api_key=''):
    user = dict(
        domain=domain,
        username=username,
        api_version=API_VERSION,
    )
    if api_key:
        user['api_key'] = api_key
        return user
    elif password:
        auth = Requester(
            url_template="http://{domain}/auth/token/",
            method='post',
            url_args=dict(domain=domain),
            data=dict(
                username=username,
                password=password,
            ),
        )
        xml = auth.response.text
        root = etree.fromstring(xml)
        user['api_key'] = root.find("api_key").text
        return user
    else:
        raise Exception("Either password or API key must be supplied")
コード例 #3
0
def post_internal_id(user_cred, reporting_org_id, internal_identifier, pk):
    try:
        internal_org_id = Requester(
            url_template="http://{domain}/rest/v1/internal_organisation_id/",
            method='post',
            url_args=user_cred,
            headers={
                'Content-type': 'application/json',
                'Accept': 'application/json',
                'Encoding': 'utf-8',
                'Authorization': 'Token {}'.format(user_cred['api_key'])
            },
            data=json.dumps(
                dict(
                    recording_org=reporting_org_id,
                    referenced_org=pk,
                    identifier=internal_identifier,
                )),
            accept_codes=[HTTP_201_CREATED],
        )
    except Exception, e:
        return "Error creating internal ID: {extra}", dict(
            pk=pk,
            event=ERROR_CREATE_INTERNAL_ID,
            internal_org_id=internal_identifier,
            extra=e.message,
        )
コード例 #4
0
def user_org(user_cred):
    try:
        profile = Requester(
            url_template="http://{domain}/api/{api_version}/user_profile/?"
            "format=json&api_key={api_key}&username={username}&user__username={username}",
            url_args=user_cred,
        )
        # find the organisation ID in the path string, e.g. "/api/v1/organisation/42/"
        #non-intuitively split() returns an empty string first and last, thus [-2]
        return profile.response.json()['objects'][0]['organisation'].split(
            '/')[-2]
    except Exception, e:
        print "{message}".format(message=e.message)
        return None
コード例 #5
0
def get_project_count(user, **q_args):
    """
    Look for a project
    """
    url_args = user
    url_args.update(extra_args="&".join(
        ["{}={}".format(item[0], item[1]) for item in q_args.items()]))
    try:
        project = Requester(
            url_template="http://{domain}/api/{api_version}/project/"
            "?format=json&api_key={api_key}&username={username}&{extra_args}",
            url_args=url_args,
        )
    except Exception, e:
        print "{message}".format(message=e.message)
        return False, None
コード例 #6
0
def load_xml(location):
    "Load XMl either from file or from a URL"
    xml = ''
    if location[:4] == 'http':
        try:
            xml = Requester(
                url_template=location,
                headers={
                    'content-type': 'application/xml',
                    'encoding': 'utf-8',
                },
                accept_codes=[HTTP_200_OK],
            )
        except Exception, e:
            return ''
        if xml.response.status_code is HTTP_200_OK:
            return xml.response.text.encode('utf-8')
コード例 #7
0
def put_an_activity(activity_element, pk, url_args):
    url_args.update(pk=pk)
    try:
        iati_id = activity_element.findall('iati-identifier')[0].text
        project = Requester(
            url_template=
            "http://{domain}/api/{api_version}/iati_activity/{pk}/?format=xml&api_key={api_key}&username={username}",
            method='put',
            url_args=url_args,
            headers={
                'content-type': 'application/xml',
                'encoding': 'utf-8'
            },
            data=etree.tostring(activity_element),
            accept_codes=[HttpNoContent.status_code],
        )
    except Exception, e:
        return False, "{extra}", dict(iati_id=iati_id,
                                      event=ERROR_EXCEPTION,
                                      extra=e.message)
コード例 #8
0
def post_org(internal_org_id, org_as_dict, user_cred):
    try:
        organisation = Requester(
            url_template="http://{domain}/rest/v1/organisation/",
            method='post',
            url_args=user_cred,
            headers={
                'Content-type': 'application/json',
                'Accept': 'application/json',
                'Encoding': 'utf-8',
                'Authorization': 'Token {}'.format(user_cred['api_key'])
            },
            data=json.dumps(org_as_dict),
            accept_codes=[HTTP_201_CREATED],
        )
    except Exception, e:
        return False, "{extra}", dict(
            internal_org_id=internal_org_id,
            event=ERROR_EXCEPTION,
            extra=e.message,
        )