4fbbc0668ef1fb63e43690f71494394e85383bd4
[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.forward({
38             'action': 'get',
39             'object': 'local:object', # proposed to replace metadata:table
40             'fields':     fields 
41         })
42
43         if result['code'] == 1: # warning
44             messages.warning(request, result['description'])
45         elif result['code'] == 2:
46             messages.error(request, result['description'])
47             # XXX FAIL HERE XXX
48
49         rows = result.ok_value()
50 # API errors will be handled by the outer logic
51 #        if not rows:
52 #            print "Failed to retrieve metadata",rows_result.error()
53 #            rows=[]
54         self.hash_by_object = dict ( [ (row['table'], row) for row in rows ] )
55         # save for next time we use offline mode
56         if debug and rows:
57             with file(offline_filename,'w') as f:
58                 f.write(json.dumps(self.hash_by_object))
59
60     def to_json(self):
61         return json.dumps(self.hash_by_object)
62
63     def details_by_object (self, object):
64         return self.hash_by_object[object]
65
66     def sorted_fields_by_object (self, object):
67         return self.hash_by_object[object]['column'].sort()
68
69     def get_field_type(self, object, field):
70         print "Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon"
71         return field