fix myplugin JS example on_new_record function
[myslice.git] / manifold / manifoldproxy.py
1 import json
2 # this is for django objects only
3 #from django.core import serializers
4 from django.http                import HttpResponse, HttpResponseForbidden
5
6 #from manifold.manifoldquery import ManifoldQuery
7 from manifold.core.query        import Query
8 from manifold.core.result_value import ResultValue
9 from manifold.manifoldapi       import ManifoldAPI
10 from manifold.manifoldresult    import ManifoldException
11 from manifold.util.log          import Log
12
13 debug=False
14 debug=True
15
16 # add artificial delay in s
17 debug_spin=0
18 #debug_spin=1
19
20 # pretend the server only returns - empty lists to 'get' requests - this is to mimick 
21 # misconfigurations or expired credentials or similar corner case situations
22 debug_empty=False
23 #debug_empty=True
24
25 # turn this on if you want the fastest possible (locally cached) feedback
26 # beware that this is very rough though...
27 work_offline=False
28 #work_offline=True
29
30 # this view is what the javascript talks to when it sends a query
31 # see also
32 # myslice/urls.py
33 # as well as 
34 # static/js/manifold.js
35 def proxy (request,format):
36     """the view associated with /manifold/proxy/ 
37 with the query passed using POST"""
38     
39     # expecting a POST
40     if request.method != 'POST':
41         print "manifoldproxy.api: unexpected method %s -- exiting"%request.method
42         return 
43     # we only support json for now
44     # if needed in the future we should probably cater for
45     # format_in : how is the query encoded in POST
46     # format_out: how to serve the results
47     if format != 'json':
48         print "manifoldproxy.proxy: unexpected format %s -- exiting"%format
49         return
50     try:
51         # translate incoming POST request into a query object
52         if debug: print 'manifoldproxy.proxy: request.POST',request.POST
53         manifold_query = Query()
54         #manifold_query = ManifoldQuery()
55         manifold_query.fill_from_POST(request.POST)
56         offline_filename="offline-%s-%s.json"%(manifold_query.action,manifold_query.object)
57         # retrieve session for request
58
59         # We allow some requests to use the ADMIN user account
60         if (manifold_query.get_from() == 'local:user' and manifold_query.get_action() == 'create') or (manifold_query.get_from() == 'local:platform' and manifold_query.get_action() == 'get'):
61             print "W: Used hardcoded demo account for admin queries"
62             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': 'demo', 'AuthString': 'demo'}
63         else:
64             manifold_api_session_auth = request.session['manifold']['auth']
65
66         if debug_empty and manifold_query.action.lower()=='get':
67             json_answer=json.dumps({'code':0,'value':[]})
68             print "By-passing : debug_empty & 'get' request : returning a fake empty list"
69             return HttpResponse (json_answer, mimetype="application/json")
70         ### patch : return the latest one..
71         if work_offline:
72             # if that won't work then we'll try to update anyways
73             try:
74                 with (file(offline_filename,"r")) as f:
75                     json_answer=f.read()
76                 print "By-passing : using contents from %s"%offline_filename
77                 return HttpResponse (json_answer, mimetype="application/json")
78             except:
79                 import traceback
80                 traceback.print_exc()
81                 print "Could not run in offline mode, PROCEEDING"
82                 pass
83                 
84         # actually forward
85         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
86         if debug: print '===> manifoldproxy.proxy: sending to backend', manifold_query
87         # for the benefit of the python code, manifoldAPI raises an exception if something is wrong
88         # however in this case we want to propagate the complete manifold result to the js world
89
90         result = manifold_api.forward(manifold_query.to_dict())
91
92         # XXX TEMP HACK
93         if 'description' in result and result['description'] and isinstance(result['description'], (tuple, list, set, frozenset)):
94             result [ 'description' ] = [ ResultValue.to_html (x) for x in result['description'] ]
95
96         json_answer=json.dumps(result)
97         # if in debug mode we save this so we can use offline mode later
98         if debug:
99             with (file(offline_filename,"w")) as f:
100                 f.write(json_answer)
101
102         # this is an artificial delay added for debugging purposes only
103         if debug_spin>0:
104             print "Adding additional artificial delay",debug_spin
105             import time
106             time.sleep(debug_spin)
107
108         return HttpResponse (json_answer, mimetype="application/json")
109
110     except Exception,e:
111         print "** PROXY ERROR **",e
112         import traceback
113         traceback.print_exc()
114
115 #################### 
116 # see CSRF_FAILURE_VIEW in settings.py
117 # the purpose of redefining this was to display the failure reason somehow
118 # this however turns out disappointing/not very informative
119 failure_answer=[ "csrf_failure" ]
120 def csrf_failure(request, reason=""):
121     print "CSRF failure with reason '%s'"%reason
122     return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")