'Set a specific permission on a library item, leaving all other current permissions on the item alone.
Permission looks like: { Action.action : [ Role, Role ] }'

def set_library_item_permission(self, library_item, permission={}):

    flush_needed = False
    for (action, roles) in permission.items():
        if isinstance(action, Action):
            action = action.action
        for item_permission in library_item.actions:
            if (item_permission.action == action):
                self.sa_session.delete(item_permission)
                flush_needed = True
        if isinstance(library_item, self.model.LibraryDataset):
            for item_permission in [self.model.LibraryDatasetPermissions(action, library_item, role) for role in roles]:
                self.sa_session.add(item_permission)
                flush_needed = True
        elif isinstance(library_item, self.model.LibraryPermissions):
            for item_permission in [self.model.LibraryPermissions(action, library_item, role) for role in roles]:
                self.sa_session.add(item_permission)
                flush_needed = True
    if flush_needed:
        self.sa_session.flush()
