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