5. Working with Agents

Update an Agent implementation

In the definition section add

    def update_agent(api_url, auth_token, agent_type, agent_id, agent_model):
       '''create an agent and return the new agent record'''
       data = json.JSONEncoder().encode(agent_model).encode('utf-8')
       url = api_url+agent_type_path(agent_type)+'/'+str(agent_id)
       req = urllib.request.Request(
            url = url,
            data = None,
            headers = {'X-ArchivesSpace-Session': auth_token},
            method = 'POST')
       try:
            response = urllib.request.urlopen(req, data)
       except urllib.error.URLError as e:
            print(e.reason)
            return None
       except urllib.error.HTTPError as e:
            print(e.code)
            print(e.read())
            return None
       src = response.read().decode('utf-8')
       return json.JSONDecoder().decode(src)

In the test section add

        # Update the record we just created
        agent_type = input('Enter agent type: ')
        agent_id = int(input('Enter agent id to update: '))
        note_text = input('Enter some text to add as a note: ')
        agent_model = list_agent(api_url, auth_token, agent_type, agent_id)
    
        note_count = len(agent_model['notes'])
        if (note_count > 0):
            print('The existing notes are', json.dumps(agent_model['notes'], indent=4))
    
        new_note = {
            'jsonmodel_type': 'note_bioghist',
            'persistent_id': 'urn:test.a.note.to.self/'+str(note_count+1),
            'label': 'Personal note to self',
            'subnotes': [
                {
                    'jsonmodel_type': 'note_text',
                    'content': note_text,
                    'publish': True
                }
            ],
            'publish':True
        }
        # now adding a new note
        agent_model['notes'].append(new_note)
        print("Added a note", json.dumps(agent_model['notes'], indent=4))
        result = update_agent(api_url, auth_token, agent_type, 3, agent_model)
        print('Response was', json.dumps(result, indent=4))

Notice the specifics of the test. The tests are brittle. Debugging the submitted record if painful. Just no two ways about it. curl can sometimes be a better friend than Python for debugging http error responses (the Postman app can also prove really helpful: https://www.getpostman.com/)

Full listing agent.py