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