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