Skip to content

Instantly share code, notes, and snippets.

@nigelbabu
Created September 30, 2013 05:55
Show Gist options
  • Save nigelbabu/6759804 to your computer and use it in GitHub Desktop.
Save nigelbabu/6759804 to your computer and use it in GitHub Desktop.
Quick script to reverse the order of resources in a CKAN dataset.
#!/usr/bin/env python
import requests
import json
def main():
# Change this to actual API key
apikey = 'XXX'
# Change if required to correct CKAN url. No trailing slash.
ckan_url = 'http://127.0.0.1:5000'
# Change to name or ID of dataset with 2 or more resources
dataset_id = 'dataset_id_here'
headers = {'Authorization': apikey, 'content-type': 'application/json'}
res = requests.get('{0}/api/3/action/package_show'.format(ckan_url), params={'id': dataset_id})
package = res.json()
# print resource id, position, and description before reorder
for resource in package['result']['resources']:
print resource['id'], resource['position'], resource['description']
# Use list.sort to reverse the ordering of the resources
package['result']['resources'].sort(key=lambda x: x['position'], reverse=True)
res = requests.post('{0}/api/3/action/package_update'.format(ckan_url), data=json.dumps(package['result']), headers=headers)
package = res.json()
# print reversed list
for resource in package['result']['resources']:
print resource['id'], resource['position'], resource['description']
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment