420821c8c86261a4b0971411f9cdeae8c7fc89be
[myslice.git] / manifold / metadata.py
1 import json 
2 import os.path
3
4 from manifold.manifoldresult import ManifoldResult
5 from manifold.manifoldapi import ManifoldAPI
6
7 debug=False
8 debug=True
9
10 # turn this on if you want to work offline
11 work_offline=False
12 #work_offline=True
13
14 class MetaData:
15
16     def __init__ (self, auth):
17         self.auth=auth
18         self.hash_by_object={}
19
20     def fetch (self):
21         offline_filename="%s/../offline-metadata.json"%os.path.dirname(__file__)
22         if work_offline:
23             try:
24                 with file(offline_metadata) as f:
25                     self.hash_by_object=json.loads(f.read())
26                 return
27             except:
28                 print "metadata.work_offline: failed to decode %s"%offline_filename
29         manifold_api = ManifoldAPI(self.auth)
30         fields = ['table', 'column.name', 'column.qualifier', 'column.type', 'column.is_array', 'column.description', 'column.default', 'key', 'capability']
31         #fields = ['table', 'column.column',
32         #          'column.description','column.header', 'column.title',
33         #          'column.unit', 'column.info_type',
34         #          'column.resource_type', 'column.value_type',
35         #          'column.allowed_values', 'column.platforms.platform',
36         #          'column.platforms.platform_url']
37         result = manifold_api.Get({
38             'object': 'local:object', # proposed to replace metadata:table
39             'fields':     fields 
40         })
41
42         if result['code'] == 1: # warning
43             messages.warning(request, result['description'])
44         elif result['code'] == 2:
45             messages.error(request, result['description'])
46             # XXX FAIL HERE XXX
47
48         rows = result.ok_value()
49 # API errors will be handled by the outer logic
50 #        if not rows:
51 #            print "Failed to retrieve metadata",rows_result.error()
52 #            rows=[]
53         self.hash_by_object = dict ( [ (row['table'], row) for row in rows ] )
54         # save for next time we use offline mode
55         if debug and rows:
56             with file(offline_filename,'w') as f:
57                 f.write(json.dumps(self.hash_by_object))
58
59     def to_json(self):
60         return json.dumps(self.hash_by_object)
61
62     def details_by_object (self, object):
63         return self.hash_by_object[object]
64
65     def sorted_fields_by_object (self, object):
66         return self.hash_by_object[object]['column'].sort()
67
68     def get_field_type(self, object, field):
69         print "Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon"
70         return field