wip
[myslice.git] / manifold / metadata.py
1 import json 
2
3 from manifold.manifoldresult import ManifoldResult
4 from manifold.manifoldapi import ManifoldAPI
5
6 debug=False
7 debug=True
8
9 # turn this on if you want to work offline
10 work_offline=False
11 #work_offline=True
12
13 class MetaData:
14
15     def __init__ (self, auth):
16         self.auth=auth
17         self.hash_by_subject={}
18
19         # XXX Retrieve all metadata the first time we instanciate the class
20         self.fetch()
21
22     def fetch (self):
23         offline_filename="offline-metadata.json"
24         if work_offline:
25             try:
26                 with file(offline_metadata) as f:
27                     self.hash_by_subject=json.loads(f.read())
28                 return
29             except:
30                 print "metadata.work_offline: failed to decode %s"%offline_filename
31         manifold_api = ManifoldAPI(self.auth)
32         fields = ['table', 'column.column',
33                   'column.description','column.header', 'column.title',
34                   'column.unit', 'column.info_type',
35                   'column.resource_type', 'column.value_type',
36                   'column.allowed_values', 'column.platforms.platform',
37                   'column.platforms.platform_url']
38         rows_result = manifold_api.Get({
39             'fact_table': 'local:objects', # proposed to replace metadata:table
40             'fields':     fields 
41         })
42 #old#        rows_result = manifold_api.Get('metadata:table', [], [], fields)
43         rows = rows_result.ok_value()
44         if not rows:
45             print "Failed to retrieve metadata",rows_result.error()
46             rows=[]
47         self.hash_by_subject = dict ( [ (row['table'], row) for row in rows ] )
48         # save for next time we use offline mode
49         if debug:
50             with file(offline_filename,'w') as f:
51                 f.write(json.dumps(self.hash_by_subject))
52
53     def to_json(self):
54         return json.dumps(self.hash_by_subject)
55
56     def details_by_subject (self, subject):
57         return self.hash_by_subject[subject]
58
59     def sorted_fields_by_subject (self, subject):
60         return self.hash_by_subject[subject]['columns'].sort()