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