Groups migrated from datagov
Groups migrated from datagov


Former-commit-id: 3aeee877b6cbf00b3303cddd31ca4790fb66f24c

--- a/documents/datagov-export.py
+++ b/documents/datagov-export.py
@@ -13,7 +13,7 @@
 #ckan = ckanclient.CkanClient(base_location='http://localhost:5000/api',    api_key='b47b24cd-591d-40c1-8677-d73101d56d1b')
 api_key = 'b3ab75e4-afbb-465b-a09d-8171c8c69a7a'
 ckan = ckanclient.CkanClient(base_location='http://data.disclosurelo.gs/api',
-    api_key=api_key)
+                             api_key=api_key)
 ckandirect = ckanapi.RemoteCKAN('http://data.disclosurelo.gs', api_key=api_key)
 couch = couchdb.Server('http://127.0.0.1:5984/')
 #couch = couchdb.Server('http://192.168.1.113:5984/')
@@ -27,6 +27,7 @@
     'iec_ext': ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi',
                 'zebi', 'yobi'),
 }
+
 
 def human2bytes(s):
     """
@@ -94,7 +95,7 @@
 #todo "{'name': [u'Url must be purely lowercase alphanumeric (ascii) characters and these symbols: -_']}"
 # http://data.gov.au/dataset/australian-domestic-regional-and-international-airline-activity-%E2%80%93-time-series/
 def name_munge(input_name):
-    return  munge(input_name.replace(' ', '').replace('.', '_').replace('&', 'and'))
+    return munge(input_name.replace(' ', '').replace('.', '_').replace('&', 'and'))
     #[:100]
     #return input_name.replace(' ', '').replace('.', '_').replace('&', 'and')
 
@@ -117,6 +118,7 @@
         raise Exception(licencename + " not found");
     return map[licencename];
 
+
 docsdb = couch['disclosr-documents']
 
 if __name__ == "__main__":
@@ -124,13 +126,12 @@
     for doc in docsdb.view('app/datasets'):
         print doc.id
 
-
         if doc.value['url'] != "http://data.gov.au/data/" and doc.value['agencyID'] != "qld":
 
 
-
             # Collect the package metadata.
-            pkg_name = filter( lambda x: x in '0123456789abcdefghijklmnopqrstuvwxyz-_',doc.value['url'].replace("http://data.gov.au/dataset/",'').replace('/','')[:100]);
+            pkg_name = filter(lambda x: x in '0123456789abcdefghijklmnopqrstuvwxyz-_',
+                              doc.value['url'].replace("http://data.gov.au/dataset/", '').replace('/', '')[:100]);
             print pkg_name
             #add to or create organization using direct API
             org_name = name_munge(doc.value['metadata']["Agency"][:100])
@@ -139,15 +140,15 @@
                 #print orgs_list
                 if org_name not in orgs_list:
                     try:
-                        print "org not found, creating "+org_name
-                        ckandirect.action.organization_create(name = org_name,   title= doc.value['metadata']["Agency"],
-                                                              description= doc.value['metadata']["Agency"])
+                        print "org not found, creating " + org_name
+                        ckandirect.action.organization_create(name=org_name, title=doc.value['metadata']["Agency"],
+                                                              description=doc.value['metadata']["Agency"])
                         orgs_list.append(org_name)
                     except ckanapi.ValidationError, e:
                         print e
                         raise LoaderError('Unexpected status')
                 else:
-                    print "org found, adding dataset to "+org_name
+                    print "org found, adding dataset to " + org_name
 
             org = ckandirect.action.organization_show(id=org_name)
             # todo cache org names -> id mapping
@@ -158,11 +159,7 @@
                         tags = tags + doc.value['metadata']["Keywords / Tags"]
                     else:
                         tags = tags + [doc.value['metadata']["Keywords / Tags"]]
-                if 'data.gov.au Category' in doc.value['metadata'].keys() and len(doc.value['metadata']['data.gov.au Category']) > 0:
-                    if hasattr(doc.value['metadata']['data.gov.au Category'], '__iter__'):
-                        tags = tags + doc.value['metadata']['data.gov.au Category']
-                    else:
-                        tags = tags + [doc.value['metadata']['data.gov.au Category']]
+
                 tags = [re.sub('[^a-zA-Z0-9-_.]', '', tag.replace('&', 'and')).lower() for tag in tags if tag]
                 #print tags
                 package_entity = {
@@ -192,6 +189,46 @@
                         ckan.last_status, pkg_name, e.args))
             pkg = ckan.package_entity_get(pkg_name)
 
+            # add dataset to group(s)
+            groups = []
+            if 'data.gov.au Category' in doc.value['metadata'].keys() and len(
+                    doc.value['metadata']['data.gov.au Category']) > 0:
+                if hasattr(doc.value['metadata']['data.gov.au Category'], '__iter__'):
+                    groups = groups + doc.value['metadata']['data.gov.au Category']
+                else:
+                    groups = groups + [doc.value['metadata']['data.gov.au Category']]
+
+            for group_name in groups:
+                group_url = name_munge(group_name[:100])
+                try:
+                    print ckan.group_entity_get(group_url)
+
+                    # Update the group details
+                    group_entity = ckan.last_message
+                    print "group "+group_name+" exists"
+                    if 'packages' in group_entity.keys():
+                        group_entity['packages'] = list(set(group_entity['packages'] + [pkg_name]))
+                    else:
+                        group_entity['packages'] = [pkg_name]
+                    ckan.group_entity_put(group_entity)
+                except CkanApiError, e:
+                    if ckan.last_status == 404:
+                        print "group "+group_name+" does not exist, creating"
+                        group_entity = {
+                            'name': group_url,
+                            'title': group_name,
+                            'description': group_name,
+                            'packages': [pkg_name]
+                        }
+                        #print group_entity
+                        ckan.group_register_post(group_entity)
+                    elif ckan.last_status == 409:
+                        print "group already exists"
+                    else:
+                        raise LoaderError('Unexpected status %s adding to group under \'%s\': %r' % (
+                            ckan.last_status, pkg_name, e.args))
+
+            # add resources (downloadable data files)
             if 'Download' in doc.value['metadata'].keys():
                 try:
 
@@ -211,7 +248,8 @@
                                 name = resource['name']
                             print resource
                             ckan.add_package_resource(pkg_name, resource['href'], name=name, resource_type='data',
-                                format=format, size=human2bytes(resource['size'].replace(',', '')))
+                                                      format=format,
+                                                      size=human2bytes(resource['size'].replace(',', '')))
                     else:
                         print "resources already exist"
                 except CkanApiError, e: