Merge branch 'onelab' of ssh://git.onelab.eu/git/myslice into onelab
authorYasin Rahman <loic.baron@lip6.fr>
Thu, 2 Apr 2015 16:15:47 +0000 (18:15 +0200)
committerYasin Rahman <loic.baron@lip6.fr>
Thu, 2 Apr 2015 16:15:47 +0000 (18:15 +0200)
69 files changed:
Makefile
README.django-1.7 [new file with mode: 0644]
activity/__init__.py
localauth/__init__.py [moved from auth/__init__.py with 100% similarity]
localauth/manifoldbackend.py [moved from auth/manifoldbackend.py with 68% similarity]
localauth/models.py [moved from auth/models.py with 100% similarity]
localauth/static/css/login.css [moved from auth/static/css/login.css with 100% similarity]
localauth/static/css/logout.css [moved from auth/static/css/logout.css with 100% similarity]
localauth/static/img/form_input_password.png [moved from auth/static/img/form_input_password.png with 100% similarity]
localauth/static/js/logout.js [moved from auth/static/js/logout.js with 100% similarity]
localauth/tests.py [moved from auth/tests.py with 100% similarity]
localauth/views.py [moved from auth/views.py with 87% similarity]
manifoldapi/manifoldapi.py
manifoldapi/manifoldproxy.py
manifoldapi/manifoldresult.py
manifoldapi/metadata.py
myslice/components.py
myslice/settings.py
myslice/urls.py
plugins/form/__init__.py
plugins/querygrid/__init__.py
plugins/querytable/__init__.py
plugins/univbris/__init__.py
plugins/univbrisfoam/__init__.py
plugins/univbrisfv/__init__.py
plugins/univbristopo/__init__.py
plugins/univbrisvtam/__init__.py
portal/accountview.py
portal/actions.py
portal/dashboardview.py
portal/emailactivationview.py
portal/forms.py
portal/homeview.py
portal/institution.py
portal/joinview.py
portal/managementtababout.py
portal/managementtabrequests.py
portal/manageuserview.py
portal/models.py
portal/native_migrations/0001_initial.py [new file with mode: 0644]
portal/native_migrations/__init__.py [new file with mode: 0644]
portal/platformview.py
portal/projectrequestview.py
portal/registrationview.py
portal/reputationview.py
portal/resourceview.py
portal/slicerequestview.py
portal/sliceresourceview.py
portal/slicetabexperiment.py
portal/univbrisview.py
portal/validationview.py
portal/views/__init__.py
rest/__init__.py
rest/create.py
rest/get.py
rest/initscript.py
rest/sfa_api.py
rest/update.py
sample/tabview.py
sample/topmenuvalidationview.py
ui/topmenu.py
unfold/collectstatic.py
unfold/composite.py
unfold/loginrequired.py
unfold/page.py
unfold/plugin.py
unfold/prelude.py
unfold/sessioncache.py [new file with mode: 0644]
unfold/tests.py

index 80d49c4..6f557ba 100644 (file)
--- a/Makefile
+++ b/Makefile
@@ -96,6 +96,9 @@ redo-templates: clean-templates templates
 myfiles: force
        @git ls-files | egrep -v 'insert(_|-)above|third-party/|to-be-integrated/'
 
+pyfiles: force
+       @git ls-files | grep '\.py$$'
+
 # in general it's right to rely on the contents as reported by git
 tags: force
        $(MAKE-SILENT) myfiles | xargs etags
diff --git a/README.django-1.7 b/README.django-1.7
new file mode 100644 (file)
index 0000000..382c422
--- /dev/null
@@ -0,0 +1,30 @@
+Thierry Parmentelat <thierry.parmentelat@inria.fr>
+
+As of March 31 2015, the code should be mostly ready for django-1.7,
+with the following restrictions
+
+* migrations : django-1.7 comes with its own native migrations system
+  and so south is not needed/recommended any longer. So for now we have a
+  version of such native migrations that does a one-shot setup of a db
+  schema but this is stored in
+
+  portal/native_migrations
+
+  instead of the standard location
+
+  portal/migrations
+
+  because this one is still expected to hold south code with earlier djangos
+  You might need to rename native_migrations/ into migrations/ before
+  running manage.py migrate in the first place
+
+* testing quite a few issues related to 1.7 have been addressed but it
+  would be presomptuous to state that things were tested very
+  thoroughly, far from that.
+
+  So please use with care and let meknow of any additional issues
+
+
+
+  
+
index 4719a61..62fbc9e 100644 (file)
@@ -14,6 +14,8 @@ import base64
 import time
 import datetime
 from myslice.configengine import ConfigEngine
+from myslice.settings import logger
+
 
 config = ConfigEngine()
 if config.activity and config.activity.apikey :
@@ -37,10 +39,10 @@ else :
 def logWrite(request, action, message, objects = None):
     
     if not apikey :
-        print "===============>> activity: no apikey"
+        logger.info("===============>> activity: no apikey")
         return
     if not secret :
-        print "===============>> activity: no secret"
+        logger.info("===============>> activity: no secret")
         return
     
     timestamp = time.mktime(datetime.datetime.today().timetuple())
@@ -69,12 +71,11 @@ def logWrite(request, action, message, objects = None):
     
     try :
         result = urllib2.urlopen(server, urllib.urlencode(log))
-        print "===============>> activity: %s <%s> %s" % (action, request.user,message)
+        logger.info("===============>> activity: {} <{}> {}".format(action, request.user,message))
         content = result.read()
     except urllib2.URLError as e:
-        print "===============>> activity: connection to " + server + " impossible, could not log action"
-        print e.strerror
-        print ""
+        logger.error("===============>> activity: connection to {} impossible, could not log action".format(server))
+        logger.error(e.strerror)
 
 def log(request, action, message, objects = None):
     # Create a new thread in Daemon mode to send the log entry
@@ -93,4 +94,4 @@ def getClientIp(request):
 #
 # sign the request with the secret key
 def sign(secret, message):
-    return hmac.new(secret, msg=message, digestmod=hashlib.sha256).hexdigest()
\ No newline at end of file
+    return hmac.new(secret, msg=message, digestmod=hashlib.sha256).hexdigest()
similarity index 100%
rename from auth/__init__.py
rename to localauth/__init__.py
similarity index 68%
rename from auth/manifoldbackend.py
rename to localauth/manifoldbackend.py
index c7ac7fa..c2899e9 100644 (file)
@@ -7,6 +7,8 @@ from manifold.core.query        import Query
 
 from myslice.settings import config, logger, DEBUG
 
+from unfold.sessioncache import SessionCache
+
 # Name my backend 'ManifoldBackend'
 class ManifoldBackend:
 
@@ -28,13 +30,14 @@ class ManifoldBackend:
             sessions_result = api.forward(Query.create('local:session').to_dict())
             sessions = sessions_result.ok_value()
             if not sessions:
-                logger.error("GetSession failed", sessions_result.error())
+                logger.error("GetSession failed: {}".format(sessions_result.error()))
                 return
             session = sessions[0]
-            logger.debug("SESSION : %s" % session)
+            logger.debug("SESSION : {}".format(session))
             
             # Change to session authentication
-            api.auth = {'AuthMethod': 'session', 'session': session['session']}
+            session_auth = {'AuthMethod': 'session', 'session': session['session']}
+            api.auth = session_auth
             self.api = api
 
             # Get account details
@@ -42,19 +45,21 @@ class ManifoldBackend:
             persons_result = api.forward(Query.get('local:user').to_dict())
             persons = persons_result.ok_value()
             if not persons:
-                logger.error("GetPersons failed",persons_result.error())
+                logger.error("GetPersons failed: {}".format(persons_result.error()))
                 return
             person = persons[0]
-            logger.debug("PERSON : %s" % person)
-            #logger.info("%s %s <%s> logged in" % (person['config']['first_name'], person['config']['last_name'], person['config']['email']))
-
-            request.session['manifold'] = {'auth': api.auth, 'person': person, 'expires': session['expires']}
-        except ManifoldException, e:
-            logger.error("Manifold Auth Backend: %s" % e.manifold_result)
-        except Exception, e:
-            logger.error("Manifold Auth Backend: %s" % e)
-            #import traceback
-            #traceback.print_exc()
+            logger.debug("PERSON : {}".format(person))
+            #logger.info("{} {} <{}> logged in"\
+            #    .format(person['config']['first_name'], person['config']['last_name'], person['config']['email']))
+
+            SessionCache().store_auth(request, session_auth)
+
+        except ManifoldException as e:
+            logger.error("ManifoldException in Auth Backend: {}".format(e.manifold_result))
+        except Exception as e:
+            logger.error("Exception in Manifold Auth Backend: {}".format(e))
+            import traceback
+            logger.error(traceback.format_exc())
             return None
 
         try:
similarity index 100%
rename from auth/models.py
rename to localauth/models.py
similarity index 100%
rename from auth/tests.py
rename to localauth/tests.py
similarity index 87%
rename from auth/views.py
rename to localauth/views.py
index b959e73..bcba326 100644 (file)
@@ -1,6 +1,8 @@
 from django.contrib.auth import logout
 from django.http import HttpResponseRedirect
 
+from myslice.settings import logger
+
 import activity.user
 
 # hard question : where should we redirect requests to logout if user is not logged in ?
@@ -8,7 +10,7 @@ def logout_user (request):
     # check that we're indeed logged in
     if not request.user.is_authenticated():
         return HttpResponseRedirect ('/')
-    print "LOGGING OUT"
+    logger.info("LOGGING OUT")
     
     # log user activity
     activity.user.logout(request)
index 9a99991..2edecdd 100644 (file)
@@ -1,14 +1,17 @@
 # Manifold API Python interface
-import copy, xmlrpclib, ssl
-from myslice.settings import config, logger, DEBUG
+import copy
+import xmlrpclib
+import ssl
 
 from django.contrib import messages
 from django.shortcuts import redirect
-from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException
+
 from manifold.core.result_value import ResultValue
+from manifoldresult import ManifoldResult, ManifoldCode, ManifoldException, truncate_result
+
+from unfold.sessioncache import SessionCache
 
-debug_deep=False
-#debug_deep=True
+from myslice.settings import config, logger
 
 class ManifoldAPI:
 
@@ -25,7 +28,8 @@ class ManifoldAPI:
         # Manifold uses a self signed certificate
         # https://www.python.org/dev/peps/pep-0476/
         if hasattr(ssl, '_create_unverified_context'): 
-            self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True, context=ssl._create_unverified_context())
+            self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
+                                           context=ssl._create_unverified_context())
         else :
             self.server = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
 
@@ -39,52 +43,41 @@ class ManifoldAPI:
 
         def func(*args, **kwds):
             import time
-            
             start = time.time()
+            
+            # the message to display
+            auth_message = "<AuthMethod not set in {}>".format(self.auth) if 'AuthMethod' not in self.auth \
+                           else "[session]" if self.auth['AuthMethod'] == 'session' \
+                           else "user:{}".format(self.auth['Username']) if self.auth['AuthMethod'] == 'password' \
+                           else "anonymous" if self.auth['AuthMethod'] == 'anonymous' \
+                           else "[???]" + "{}".format(self.auth)
+            end_message = "MANIFOLD <- {}( {}( {} ) ) with auth={} to {}"\
+                          .format(methodName,
+                                  args[0]['action'] or '', 
+                                  args[0]['object'] or '',
+                                  auth_message,
+                                  self.url)
             try:
-                
-                #logger.debug("MANIFOLD %s( %s( %s ) ) to %s" % (methodName, args[0]['action'], args[0]['object'], self.url))
-                
-                if ('Username' in self.auth) :
-                    username = self.auth['Username']
-                else :
-                    username = "-"
-                
                 args += ({ 'authentication': self.auth },)
-                                
                 result = getattr(self.server, methodName)(*args, **kwds)
-                
-                logger.debug("MANIFOLD %s( %s( %s ) ) as %s to %s executed in %s seconds -> %s" % 
-                             (methodName, 
-                              args[0]['action'] or '', 
-                              args[0]['object'] or '',
-                              username,
-                              self.url, 
-                              (time.time() - start),
-                              args))
-
+                logger.debug("{} executed in {} seconds -> {}"\
+                             .format(end_message, time.time() - start, truncate_result(result)))
                 return ResultValue(**result)
 
-            except Exception, error:
-                if True: 
-                    print "===== xmlrpc catch-all exception:", error
-                    import traceback
-                    traceback.print_exc(limit=3)
+            except Exception as error:
+                logger.error("===== xmlrpc catch-all exception: {}".format(error))
+                import traceback
+                logger.error(traceback.format_exc(limit=3))
                 
                 if "Connection refused" in error:
                     raise ManifoldException ( ManifoldResult (code=ManifoldCode.SERVER_UNREACHABLE,
-                                                              output="%s answered %s" % (self.url,error)))
+                                                              output="{} answered {}".format(self.url, error)))
                 # otherwise
-                logger.error("MANIFOLD %s( %s( %s ) ) as %s to %s executed in %s seconds -> %s" % 
-                             (methodName, 
-                              args[0]['action'] or '', 
-                              args[0]['object'] or '',
-                              username,
-                              self.url, 
-                              (time.time() - start),
-                              args))
-                logger.error("MANIFOLD %s", error)
-                raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE, output = "%s" % error) )
+                logger.error("{} FAILED - executed in {} seconds"\
+                             .format(end_message, time.time() - start)) 
+                logger.error("MANIFOLD {}".format(error))
+                raise ManifoldException ( ManifoldResult (code = ManifoldCode.SERVER_UNREACHABLE,
+                                                          output = "{}".format(error)))
 
         return func
 
@@ -92,21 +85,20 @@ def _execute_query(request, query, manifold_api_session_auth):
     
     manifold_api = ManifoldAPI(auth = manifold_api_session_auth)
     
-    logger.debug("MANIFOLD QUERY : %s" % " ".join(str(query).split()))
-    #logger.debug("MANIFOLD DICT : %s" % query.to_dict())
+    logger.debug("MANIFOLD -> QUERY : {}".format(" ".join(str(query).split())))
     result = manifold_api.forward(query.to_dict())
     if result['code'] == 2:
         # this is gross; at the very least we need to logout() 
         # but most importantly there is a need to refine that test, since 
         # code==2 does not necessarily mean an expired session
         # XXX only if we know it is the issue
-        del request.session['manifold']
+        SessionCache().end_session(request)
         # Flush django session
         request.session.flush()
-        #raise Exception, 'Error running query: %r' % result
+        #raise Exception, 'Error running query: {}'.format(result)
     
     if result['code'] == 1:
-        log.warning("MANIFOLD : %s" % result['description'])
+        log.warning("MANIFOLD : {}".format(result['description']))
 
     # XXX Handle errors
     #Error running query: {'origin': [0, 'XMLRPCAPI'], 'code': 2, 'description': 'No such session: No row was found for one()', 'traceback': 'Traceback (most recent call last):\n  File "/usr/local/lib/python2.7/dist-packages/manifold/core/xmlrpc_api.py", line 68, in xmlrpc_forward\n    user = Auth(auth).check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 245, in check\n    return self.auth_method.check()\n  File "/usr/local/lib/python2.7/dist-packages/manifold/auth/__init__.py", line 95, in check\n    raise AuthenticationFailure, "No such session: %s" % e\nAuthenticationFailure: No such session: No row was found for one()\n', 'type': 2, 'ts': None, 'value': None}
@@ -114,17 +106,20 @@ def _execute_query(request, query, manifold_api_session_auth):
     return result['value'] 
 
 def execute_query(request, query):
-    if not 'manifold' in request.session or not 'auth' in request.session['manifold']:
+    
+    manifold_api_session_auth = SessionCache().get_auth(request)
+    if not manifold_api_session_auth:
         request.session.flush()
         #raise Exception, "User not authenticated"
         host = request.get_host()
         return redirect('/')
     
-    manifold_api_session_auth = request.session['manifold']['auth']
-    
     return _execute_query(request, query, manifold_api_session_auth)
 
 def execute_admin_query(request, query):
     admin_user, admin_password = config.manifold_admin_user_password()
+    if not admin_user or not admin_password:
+        logger.error("""CONFIG: you need to setup admin_user and admin_password in myslice.ini
+Some functions won't work properly until you do so""")
     admin_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
     return _execute_query(request, query, admin_auth)
index a6f29c3..a5bc20d 100644 (file)
@@ -12,7 +12,9 @@ from manifoldapi                import ManifoldAPI
 from manifoldresult             import ManifoldException
 from manifold.util.log          import Log
 
-from myslice.settings import config, logger, DEBUG
+from unfold.sessioncache import SessionCache
+
+from myslice.settings import config, logger
 
 # register activity
 import activity.slice
@@ -35,18 +37,18 @@ def proxy (request,format):
     
     # expecting a POST
     if request.method != 'POST':
-        logger.error("MANIFOLDPROXY unexpected method %s -- exiting" % request.method)
-        return HttpResponse ({"ret":0}, mimetype="application/json")
+        logger.error("MANIFOLDPROXY unexpected method {} -- exiting".format(request.method))
+        return HttpResponse ({"ret":0}, content_type="application/json")
     # we only support json for now
     # if needed in the future we should probably cater for
     # format_in : how is the query encoded in POST
     # format_out: how to serve the results
     if format != 'json':
-        logger.error("MANIFOLDPROXY unexpected format %s -- exiting" % format)
-        return HttpResponse ({"ret":0}, mimetype="application/json")
+        logger.error("MANIFOLDPROXY unexpected format {} -- exiting".format(format))
+        return HttpResponse ({"ret":0}, content_type="application/json")
     try:
         # translate incoming POST request into a query object
-        #logger.debug("MANIFOLDPROXY request.POST %s" % request.POST)
+        #logger.debug("MANIFOLDPROXY request.POST {}".format(request.POST))
 
         manifold_query = Query()
         #manifold_query = ManifoldQuery()
@@ -59,13 +61,12 @@ def proxy (request,format):
             admin_user, admin_password = config.manifold_admin_user_password()
             manifold_api_session_auth = {'AuthMethod': 'password', 'Username': admin_user, 'AuthString': admin_password}
         else:
-            if 'manifold' in request.session:
-                manifold_api_session_auth = request.session['manifold']['auth']
-            else:
-                return HttpResponse (json.dumps({'code':0,'value':[]}), mimetype="application/json")
+            manifold_api_session_auth = SessionCache().get_auth(request)
+            if not manifold_api_session_auth:
+                return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
                 
         if debug_empty and manifold_query.action.lower()=='get':
-            return HttpResponse (json.dumps({'code':0,'value':[]}), mimetype="application/json")
+            return HttpResponse (json.dumps({'code':0,'value':[]}), content_type="application/json")
                 
         # actually forward
         manifold_api= ManifoldAPI(auth=manifold_api_session_auth)
@@ -85,7 +86,7 @@ def proxy (request,format):
         #
         # resource reservation
         if (manifold_query.action.lower() == 'update') :
-            print result['value'][0]
+            logger.debug(result['value'][0])
             if 'resource' in result['value'][0] :
                 for resource in result['value'][0]['resource'] :
                     activity.slice.resource(request, 
@@ -100,13 +101,13 @@ def proxy (request,format):
         
         json_answer=json.dumps(result)
 
-        return HttpResponse (json_answer, mimetype="application/json")
+        return HttpResponse (json_answer, content_type="application/json")
 
-    except Exception,e:
-        logger.error("MANIFOLDPROXY %s" % e)
+    except Exception as e:
+        logger.error("MANIFOLDPROXY {}".format(e))
         import traceback
-        traceback.print_exc()
-        return HttpResponse ({"ret":0}, mimetype="application/json")
+        logger.error(traceback.format_exc())
+        return HttpResponse ({"ret":0}, content_type="application/json")
 
 #################### 
 # see CSRF_FAILURE_VIEW in settings.py
@@ -114,5 +115,5 @@ def proxy (request,format):
 # this however turns out disappointing/not very informative
 failure_answer=[ "csrf_failure" ]
 def csrf_failure(request, reason=""):
-    print "CSRF failure with reason '%s'"%reason
-    return HttpResponseForbidden (json.dumps (failure_answer), mimetype="application/json")
+    logger.error("CSRF failure with reason '{}'".format(reason))
+    return HttpResponseForbidden (json.dumps (failure_answer), content_type="application/json")
index 4ffe072..3680864 100644 (file)
@@ -1,3 +1,4 @@
+# black magic to define enums
 def enum(*sequential, **named):
     enums = dict(zip(sequential, range(len(sequential))), **named)
     return type('Enum', (), enums)
@@ -10,47 +11,65 @@ ManifoldCode = enum (
     SERVER_UNREACHABLE=3,
 )
 
+def truncate(result, length=50):
+    plain = "{}".format(result)
+    if len(plain) <= length-3:
+        return plain
+    else:
+        return plain[:(length-3)]+'...'
+
 _messages_ = { -1 : "Unknown", 0: "OK", 1: "Session Expired", 2: "Not Implemented", 3: "Backend server unreachable"}
 
+def truncate_result(result, length=50):
+    self = result
+    code = self['code']
+    result = "[MFresult {} (code={})".format(_messages_.get(code, "???"), code)
+    if code == 0:
+        value = self['value']
+        if isinstance(value, list):
+            result += " [value=list with {} elts]".format(len(value))
+        elif isinstance(value, dict):
+            result += " [value=dict with keys {}]".format(value.keys())
+        else:
+            result += " [value={}: {}]".format(type(value).__name__, value)
+    elif 'output' in self:
+        result += " [output={}]".format(self['output'])
+    else:
+        result += "<no output>"
+    result += "]"
+    return truncate(result, 60)
+
 # being a dict this can be used with json.dumps
 class ManifoldResult (dict):
     def __init__ (self, code=ManifoldCode.SUCCESS, value=None, output=""):
-        self['code']=code
-        self['value']=value
-        self['output']=output
+        self['code'] = code
+        self['value'] = value
+        self['output'] = output
         self['description'] = '' # Jordan: needed by javascript code
 
     def from_json (self, json_string):
         d=json.dumps(json_string)
-        for k in ['code','value','output']:
-            self[k]=d[k]
+        for k in ['code', 'value', 'output']:
+            self[k] = d[k]
 
     # raw accessors
-    def code (self): return self['code']
-    def output (self): return self['output']
+    def code (self):
+        return self['code']
+    def output (self):
+        return self['output']
 
     # this returns None if there's a problem, the value otherwise
     def ok_value (self):
-        if self['code']==ManifoldCode.SUCCESS:
+        if self['code'] == ManifoldCode.SUCCESS:
             return self['value']
 
     # both data in a single string
     def error (self):
-        return "code=%s -- %s"%(self['code'],self['output'])
+        return "code={} -- {}".format(self['code'], self['output'])
     
 
     def __repr__ (self):
-        code=self['code']
-        result="[MFresult %s (code=%s)"%(_messages_.get(code,"???"),code)
-        if code==0:
-            value=self['value']
-            if isinstance(value,list): result += " [value=list with %d elts]"%len(value)
-            elif isinstance(value,dict): result += " [value=dict with keys %s]"%value.keys()
-            else: result += " [value=%s: %s]"%(type(value).__name__,value)
-        else:
-            result += " [output=%s]"%self['output']
-        result += "]"
-        return result
+        return truncate_result(self, 60)
 
 # probably simpler to use a single class and transport the whole result there
 # instead of a clumsy set of derived classes 
@@ -58,4 +77,4 @@ class ManifoldException (Exception):
     def __init__ (self, manifold_result):
         self.manifold_result=manifold_result
     def __repr__ (self):
-        return "Manifold Exception %s"%(self.manifold_result.error())
+        return "<Manifold Exception {}>".format(self.manifold_result.error())
index 300397c..f8e9b34 100644 (file)
@@ -6,6 +6,8 @@ from manifoldapi        import ManifoldAPI
 
 from django.contrib     import messages
 
+from myslice.settings   import logger
+
 debug=False
 #debug=True
 
@@ -34,10 +36,10 @@ class MetaData:
         # xxx need a way to export error messages to the UI
         if result['code'] == 1: # warning
             # messages.warning(request, result['description'])
-            print ("METADATA WARNING -",request,result['description'])
+            logger.warning(("METADATA WARNING - {} {}".format(request,result['description'])))
         elif result['code'] == 2:
             # messages.error(request, result['description'])
-            print ("METADATA ERROR -",request,result['description'])
+            logger.error(("METADATA ERROR - {} {}".format(request,result['description'])))
             # XXX FAIL HERE XXX
             return
 
@@ -58,5 +60,6 @@ class MetaData:
         return self.hash_by_object[object]['column'].sort()
 
     def get_field_type(self, object, field):
-        if debug: print "Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon"
+        if debug:
+            logger.debug("Temp fix for metadata::get_field_type() -> consider moving to manifold.core.metadata soon")
         return field
index 84e392c..ea4d88c 100644 (file)
@@ -14,9 +14,9 @@ def urls():
             __import__(component)
             u.append( url(r'^%s/' % component, include('%s.urls' % component)) )
         except Exception, e:
-            logger.info("Cannot load component (%s): %s" % (component, e))
+            logger.error("Cannot load component ({}): {}".format(component, e))
         else:
-            logger.info("Loaded component %s" % component)
+            logger.info("Loaded component {}".format(component))
             
     return u
 
index 3f79a19..f4d0835 100644 (file)
@@ -8,7 +8,7 @@ try:
     ROOT = os.path.realpath(os.path.dirname(__file__) + '/..')
 except:
     import traceback
-    traceback.print_exc()
+    logger.error(traceback.format_exc())
 
 
 from myslice.configengine import ConfigEngine
@@ -242,15 +242,13 @@ INSTALLED_APPS = [
     # our django project
     'myslice',
     # the core of the UI
-    'auth', 
+    'localauth', 
     'manifoldapi',
     'unfold',
     # plugins
     'plugins',
     # views - more or less stable 
     'ui',
-    # managing database migrations
-    'south', 
     # Uncomment the next line to enable the admin:
      'django.contrib.admin',
        # FORGE Plugin app
@@ -259,8 +257,16 @@ INSTALLED_APPS = [
     # 'django.contrib.admindocs',
     'portal',
 ]
+# with django-1.7 we leave south and use native migrations
+# managing database migrations
+import django
+major, minor, _, _, _ = django.VERSION
+if major == 1 and minor <= 6:
+    INSTALLED_APPS.append('south')
+
 # this app won't load in a build environment
-if not building: INSTALLED_APPS.append ('rest')
+if not building:
+    INSTALLED_APPS.append ('rest')
 
 for component in components.list() :
     INSTALLED_APPS.append(component)
@@ -269,7 +275,7 @@ BROKER_URL = "amqp://myslice:myslice@localhost:5672/myslice"
 
 for aux in auxiliaries:
     if os.path.isdir(os.path.join(ROOT,aux)): 
-        print("Using devel auxiliary",aux)
+        logger.info("Using devel auxiliary {}".format(aux))
         INSTALLED_APPS.append(aux)
 
 ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window; you may, of course, use a different value.
@@ -336,7 +342,7 @@ LOGGING = {
     }
 }
 
-AUTHENTICATION_BACKENDS = ('auth.manifoldbackend.ManifoldBackend',
+AUTHENTICATION_BACKENDS = ('localauth.manifoldbackend.ManifoldBackend',
                            'django.contrib.auth.backends.ModelBackend')
 
 ### the view to redirect malformed (i.e. with a wrong CSRF) incoming requests
index f792a05..631c15e 100644 (file)
@@ -12,7 +12,12 @@ import components
 # admin.autodiscover()
 
 # to enable insert_above stuff
-from django.template.loader import add_to_builtins
+# add_to_builtins has changed location with django-1.7
+# also note this will probably go away some day
+try:
+    from django.template.loader import add_to_builtins
+except:
+    from django.template.base import add_to_builtins
 add_to_builtins('insert_above.templatetags.insert_tags')
 
 from settings import auxiliaries, INSTALLED_APPS
@@ -65,7 +70,7 @@ urls = [
     # seems to be what login_required uses to redirect ...
     (r'^accounts/login/$', portal.homeview.HomeView.as_view()),
     (r'^login/?$', portal.homeview.HomeView.as_view()),
-    (r'^logout/?$', 'auth.views.logout_user'),
+    (r'^logout/?$', 'localauth.views.logout_user'),
     #
     # the manifold proxy
     (r'^manifold/proxy/(?P<format>\w+)/?$', 'manifoldapi.manifoldproxy.proxy'),
index d4dce75..d232811 100644 (file)
@@ -5,7 +5,6 @@ class CreateForm (Plugin):
 
     def __init__ (self, **settings):
         Plugin.__init__(self, **settings)
-        print "SETTINGS", settings
         assert 'page'   in settings, "You should specify page"
         assert 'object' in settings, "You should specify object"
 
index 587637a..2a1cca5 100644 (file)
@@ -1,5 +1,7 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class QueryGrid (Plugin):
 
     """A plugin for displaying a query as a list
@@ -67,7 +69,7 @@ Current implementation makes the following assumptions
         if self.checkboxes:
             # we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
             if 'aoColumns' in self.datatables_options:
-                print 'WARNING: querygrid uses aoColumnDefs, your aoColumns spec. is discarded'
+                logger.warning('WARNING: querygrid uses aoColumnDefs, your aoColumns spec. is discarded')
                 del self.datatables_options['aoColumns']
             # set aoColumnDefs in datatables_options - might already have stuff in there
             aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
index fe486d5..60265fc 100644 (file)
@@ -1,5 +1,7 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class QueryTable (Plugin):
 
     """A plugin for displaying a query as a list
@@ -50,7 +52,7 @@ Current implementation makes the following assumptions
             _columns = columns
             _hidden_columns = []
         elif self.query:
-            print "self.query.fields = ", self.query_all.fields
+            logger.debug("self.query.fields = {}".format(self.query_all.fields))
             # Columns displayed by default
             if self.default_fields is not None:
                 _columns = [field for field in self.default_fields if not field == 'urn']
@@ -59,7 +61,7 @@ Current implementation makes the following assumptions
             if query_all:
                 # We need a list because sets are not JSON-serializable
                 if self.default_fields is not None:
-                    print self.query_all.fields
+                    logger.debug(self.query_all.fields)
                     _hidden_columns = list(self.query_all.fields - set(self.default_fields))
                 else:
                     _hidden_columns = list(self.query_all.fields - self.query.fields)
@@ -70,11 +72,11 @@ Current implementation makes the following assumptions
             _columns = []
             _hidden_columns = []
 
-        print "_columns=", _columns
+        logger.debug("_columns={}".format(_columns))
         self.columns = { self.mapping.get(c, c) : c for c in _columns }
         self.hidden_columns = { self.mapping.get(c, c) : c for c in _hidden_columns }
-        print "self.columns", self.columns
-        print "self.hidden_columns", self.hidden_columns
+        logger.debug("self.columns {}".format(self.columns))
+        logger.debug("self.hidden_columns {}".format(self.hidden_columns))
 
         self.init_key=init_key
         self.datatables_options=datatables_options
@@ -84,7 +86,7 @@ Current implementation makes the following assumptions
         if self.checkboxes:
             # we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
             if 'aoColumns' in self.datatables_options:
-                print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+                logger.warning('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
                 del self.datatables_options['aoColumns']
             # set aoColumnDefs in datatables_options - might already have stuff in there
             aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
index 89b3ec5..64322fd 100644 (file)
@@ -1,24 +1,27 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class Univbris(Plugin):
     
     def __init__ (self, query=None, **settings):
         Plugin.__init__ (self, **settings)
         self.query=query
-       self.query_uuid = query.query_uuid if query else None
-       print "called univbris plugin"
+        self.query_uuid = query.query_uuid if query else None
+        logger.info("called univbris plugin")
 
     def template_file (self):
         try:
             return "univbris_welcome.html"
-        except Exception:
-                   print "error template"
+        except Exception as e:
+            logger.error("error template {}".format(e))
 
     def requirements (self):
         reqs = {
-            'js_files' : [ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
-                           "js/manifold.js", "js/manifold-query.js",
-                           "js/unfold-helper.js",
+            'js_files' : [
+                "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
+                "js/manifold.js", "js/manifold-query.js",
+                "js/unfold-helper.js",
                 'js/univbris.js',
             ],
             'css_files': [
@@ -31,7 +34,7 @@ class Univbris(Plugin):
         # query_uuid will pass self.query results to the javascript
         # and will be available as "record" in :
         # on_new_record: function(record)
-        return ['plugin_uuid', 'domid', 'query_uuid','init_key',]
+        return ['plugin_uuid', 'domid', 'query_uuid', 'init_key', ]
 
     def export_json_settings (self):
         return True
index 254fda2..5d15c3a 100644 (file)
@@ -1,5 +1,7 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class UnivbrisFoam (Plugin):
 
     """
@@ -49,20 +51,20 @@ Current implementation makes the following assumptions
         # Until we have a proper way to access queries in Python
         self.query_all      = query_all
         self.query_all_uuid = query_all.query_uuid if query_all else None
-       self.sync_query_uuid = sync_query.query_uuid if sync_query else None
+        self.sync_query_uuid = sync_query.query_uuid if sync_query else None
         self.checkboxes     = checkboxes
         # XXX We need to have some hidden columns until we properly handle dynamic queries
         if columns is not None:
             self.columns=columns
             self.hidden_columns = []
         elif self.query:
-           self.columns = list (['testbed','head node id/port','tail node id/port','link type','selected'])
-           #replace production
+            self.columns = list (['testbed','head node id/port','tail node id/port','link type','selected'])
+            #replace production
             #self.columns = self.query.fields
             if query_all:
                 #replace production
-               self.hidden_columns = []
-               # We need a list because sets are not JSON-serializable
+                self.hidden_columns = []
+                # We need a list because sets are not JSON-serializable
                 #self.hidden_columns = #list(self.query_all.fields - self.query.fields)
             else:
                 self.hidden_columns = []
@@ -77,7 +79,7 @@ Current implementation makes the following assumptions
         if self.checkboxes:
             # we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
             if 'aoColumns' in self.datatables_options:
-                print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+                logger.warning('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
                 del self.datatables_options['aoColumns']
             # set aoColumnDefs in datatables_options - might already have stuff in there
             aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
index 6c9aef2..e2c6ab3 100644 (file)
@@ -1,5 +1,7 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class UnivbrisFv (Plugin):
 
     """
@@ -55,13 +57,13 @@ Current implementation makes the following assumptions
             self.columns=columns
             self.hidden_columns = []
         elif self.query:
-           self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
-           #replace production
+            self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
+            #replace production
             #self.columns = self.query.fields
             if query_all:
                 #replace production
-               self.hidden_columns = []
-               # We need a list because sets are not JSON-serializable
+                self.hidden_columns = []
+                # We need a list because sets are not JSON-serializable
                 #self.hidden_columns = #list(self.query_all.fields - self.query.fields)
             else:
                 self.hidden_columns = []
@@ -69,7 +71,7 @@ Current implementation makes the following assumptions
             self.columns = []
             self.hidden_columns = []
 
-       self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
+        self.columns = list (['Flowspace Name', 'Edit', 'Delete'])
         self.init_key=init_key
         self.datatables_options=datatables_options
         # if checkboxes were required, we tell datatables about this column's type
@@ -78,7 +80,7 @@ Current implementation makes the following assumptions
         if self.checkboxes:
             # we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
             if 'aoColumns' in self.datatables_options:
-                print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+                logger.warning('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
                 del self.datatables_options['aoColumns']
             # set aoColumnDefs in datatables_options - might already have stuff in there
             aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
@@ -98,12 +100,13 @@ Current implementation makes the following assumptions
     def requirements (self):
         reqs = {
             'js_files' : [ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
- "js/dataTables.js",  "js/dataTables.bootstrap.js", "js/with-datatables.js", "js/jquery.jeditable.js", 
+                           "js/dataTables.js",  "js/dataTables.bootstrap.js",
+                           "js/with-datatables.js", "js/jquery.jeditable.js", 
                            "js/manifold.js", "js/manifold-query.js", 
                            "js/unfold-helper.js",
                           # querytable.js needs to be loaded after dataTables.js as it extends 
                           # dataTableExt.afnSortData
-                         # "js/jquery-ui.min.js" "js/jquery.dataTables.editable.js", "js/jquery.validate.js",
+                          # "js/jquery-ui.min.js" "js/jquery.dataTables.editable.js", "js/jquery.validate.js",
                            "js/univbrisfv.js",#"js/univbrisfv.js",
                            ] ,
             'css_files': [ "css/dataTables.bootstrap.css",
index c9e92c9..6a9a47f 100644 (file)
@@ -1,24 +1,27 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class UnivbrisTopo(Plugin):
     
     def __init__ (self, query=None, **settings):
         Plugin.__init__ (self, **settings)
         self.query=query
-       self.query_uuid = query.query_uuid if query else None
-       print "called univbris topo plugin"
+        self.query_uuid = query.query_uuid if query else None
+        logger.info("called univbris topo plugin")
 
     def template_file (self):
-       try:
-               return "univbris_topology.html"
-       except:
-               print "error template"
+        try:
+            return "univbris_topology.html"
+        except Exception as e :
+            logger.error("error template {}".format(e))
 
     def requirements (self):
         reqs = {
-            'js_files' : [ "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
-                           "js/manifold.js", "js/manifold-query.js", 
-                           "js/unfold-helper.js",
+            'js_files' : [
+                "js/spin-presets.js", "js/spin.min.js", "js/jquery.spin.js",
+                "js/manifold.js", "js/manifold-query.js", 
+                "js/unfold-helper.js",
                 'js/univbristopo.js', 'js/d3.v2.min.js','js/tooltip.topology.js',
             ],
             'css_files': [
index bc2bf9e..50da3ee 100644 (file)
@@ -1,5 +1,7 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class UnivbrisVtam (Plugin):
     def __init__ (self, query=None, query_all=None, sync_query=None,
                   checkboxes=False, columns=None, 
@@ -7,24 +9,24 @@ class UnivbrisVtam (Plugin):
                   datatables_options={}, **settings):
         Plugin.__init__ (self, **settings)
         self.query          = query
-       self.query_uuid     = query.query_uuid if query else None
+        self.query_uuid     = query.query_uuid if query else None
         # Until we have a proper way to access queries in Python
         self.query_all      = query_all
         self.query_all_uuid = query_all.query_uuid if query_all else None
-       self.sync_query_uuid = sync_query.query_uuid if sync_query else None
+        self.sync_query_uuid = sync_query.query_uuid if sync_query else None
         self.checkboxes     = checkboxes
         # XXX We need to have some hidden columns until we properly handle dynamic queries
         if columns is not None:
             self.columns=columns
             self.hidden_columns = []
         elif self.query:
-           self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
-           #replace production
+            self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
+            #replace production
             #self.columns = self.query.fields
             if query_all:
                 #replace production
-               self.hidden_columns = []
-               # We need a list because sets are not JSON-serializable
+                self.hidden_columns = []
+                # We need a list because sets are not JSON-serializable
                 #self.hidden_columns = #list(self.query_all.fields - self.query.fields)
             else:
                 self.hidden_columns = []
@@ -32,7 +34,7 @@ class UnivbrisVtam (Plugin):
             self.columns = []
             self.hidden_columns = []
 
-       self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
+        self.columns = list (['Testbed', 'Virtualization Server', 'VM name', 'Delete'])
         self.init_key=init_key
         self.datatables_options=datatables_options
         # if checkboxes were required, we tell datatables about this column's type
@@ -41,7 +43,7 @@ class UnivbrisVtam (Plugin):
         if self.checkboxes:
             # we use aoColumnDefs rather than aoColumns -- ignore user-provided aoColumns
             if 'aoColumns' in self.datatables_options:
-                print 'WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded'
+                logger.warning('WARNING: querytable uses aoColumnDefs, your aoColumns spec. is discarded')
                 del self.datatables_options['aoColumns']
             # set aoColumnDefs in datatables_options - might already have stuff in there
             aoColumnDefs = self.datatables_options.setdefault ('aoColumnDefs',[])
index dfda182..41e4d06 100644 (file)
@@ -1,25 +1,29 @@
-from unfold.loginrequired               import LoginRequiredAutoLogoutView
-#
-#
-from manifold.core.query                import Query
-from manifoldapi.manifoldapi            import execute_query
-from portal.actions                     import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds
 #
-from unfold.page                        import Page    
-from ui.topmenu                         import topmenu_items_live, the_user
+import json, os, re, itertools, time
+from OpenSSL import crypto
+from Crypto.PublicKey import RSA
+
 #
 from django.http                        import HttpResponse, HttpResponseRedirect
 from django.contrib                     import messages
 from django.contrib.auth.decorators     import login_required
 
-from myslice.configengine           import ConfigEngine
-from myslice.theme import ThemeView
+#
+from manifold.core.query                import Query
+from manifoldapi.manifoldapi            import execute_query
+
+from unfold.loginrequired               import LoginRequiredAutoLogoutView
+from unfold.page                        import Page    
+from ui.topmenu                         import topmenu_items_live, the_user
 
+from portal.actions                     import (
+    manifold_update_user, manifold_update_account, manifold_add_account,
+    manifold_delete_account, sfa_update_user, sfa_get_user, clear_user_creds )
 from portal.account                     import Account, get_expiration
-#
-import json, os, re, itertools, time
-from OpenSSL import crypto
-from Crypto.PublicKey import RSA
+
+from myslice.settings                   import logger
+from myslice.configengine               import ConfigEngine
+from myslice.theme                      import ThemeView
 
 # requires login
 class AccountView(LoginRequiredAutoLogoutView, ThemeView):
@@ -289,11 +293,11 @@ def account_process(request):
             if user_email == request.user.email:                                          
                 authorize_query = True                                                    
             else:                                                                         
-                print "SECURITY: %s tried to update %s" % (user_email, request.user.email)
+                logger.error("SECURITY: {} tried to update {}".format(user_email, request.user.email))
                 messages.error(request, 'You are not authorized to modify another user.') 
                 return HttpResponseRedirect("/portal/account/")                               
-        except Exception,e:
-            print "Exception = %s" % e
+        except Exception as e:
+            logger.error("exception in account_process {}".format(e))
 
     for account_detail in account_details:
         for platform_detail in platform_details:
@@ -426,9 +430,9 @@ def account_process(request):
                                 messages.success(request, 'Sucess: New Keypair Generated! Delegation of your credentials will be automatic.')
                             else:
                                 raise Exception,"Keys are not matching"
-                        except Exception, e:
+                        except Exception as e:
                             messages.error(request, 'Error: An error occured during the update of your public key at the Registry, or your public key is not matching the one stored.')
-                            print "Exception in accountview ", e
+                            logger.error("Exception in accountview {}".format(e))
                         return HttpResponseRedirect("/portal/account/")
         else:
             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
@@ -591,8 +595,8 @@ def account_process(request):
                 messages.success(request, 'All Credentials cleared')
             else:
                 messages.error(request, 'Delete error: Credentials are not stored in the server')
-        except Exception,e:
-            print "Exception in accountview.py in clear_user_creds %s" % e
+        except Exception as e:
+            logger.error("Exception in accountview.py in clear_user_creds {}".format(e))
             messages.error(request, 'Account error: You need an account in myslice platform to perform this action')
         return HttpResponseRedirect("/portal/account/")
 
index 82221ab..e6dd0ea 100644 (file)
@@ -14,7 +14,7 @@ from django.core.mail               import EmailMultiAlternatives, send_mail
 
 from myslice.theme                  import ThemeView
 from myslice.configengine           import ConfigEngine
-
+from myslice.settings               import logger
 
 theme = ThemeView()
 
@@ -81,8 +81,8 @@ def authority_check_pis(request, user_email):
             pi_status = True
         return pi_status
 
-    except Exception,e:
-        print "Exception in actions.py in authority_check_pis %s" % e
+    except Exception as e:
+        logger.error("Exception in actions.py in authority_check_pis {}".format(e))
         return None
 
 
@@ -98,8 +98,8 @@ def authority_add_pis(request, authority_hrn,user_hrn):
         results = execute_query(request,query)
         newpis = authority_get_pis (request, authority_hrn)
         return newpis
-    except Exception,e: 
-        print "Exception in actions.py in authority_add_pis %s" % e
+    except Exception as e: 
+        logger.error("Exception in actions.py in authority_add_pis {}".format(e))
         return None
 
 
@@ -115,14 +115,14 @@ def authority_remove_pis(request, authority_hrn,user_hrn):
         results = execute_query(request,query)
         newpis = authority_get_pis (request, authority_hrn)
         return newpis
-    except Exception,e: 
-        print "Exception in actions.py in authority_remove_pis %s" % e
+    except Exception as e: 
+        logger.error("Exception in actions.py in authority_remove_pis {}".format(e))
         return None
 
 
 def authority_get_pi_emails(request, authority_hrn):
     pi_users = authority_get_pis(request,authority_hrn)
-    print "pi_users = %s" % pi_users
+    logger.info("pi_users = %s" % pi_users)
 
     if any(pi['pi_users'] == None or not pi['pi_users']  for pi in pi_users):
         #theme.template_name = 'email_default_recipients.txt' 
@@ -174,13 +174,13 @@ def clear_user_creds(request, user_email):
                         else:
                             return None
 
-    except Exception,e:
-        print "Exception in actions.py in clear_user_creds %s" % e
+    except Exception as e:
+        logger.error("Exception in actions.py in clear_user_creds {}".format(e))
         return None
 
 def is_pi(wsgi_request, user_hrn, authority_hrn):
     # authorities from user where user_hrn == "ple.upmc.jordan_auge"
-    print "#### actions.py is_pi authority_hrn = ", authority_hrn
+    logger.debug("#### actions.py is_pi authority_hrn = {}".format(authority_hrn))
     try:
         # CACHE PB with fields
         page = Page(wsgi_request)
@@ -192,12 +192,11 @@ def is_pi(wsgi_request, user_hrn, authority_hrn):
         query  = Query().get('myslice:user').select(user_fields).filter_by('user_hrn','==',user_hrn)
         #query = Query.get('myslice:user').filter_by('user_hrn', '==', user_hrn).select('pi_authorities')
         results = execute_query(wsgi_request, query)
-        #print "is_pi results = ", results
         for user_detail in results:
             if authority_hrn in user_detail['pi_authorities']:
                 return True
-    except Exception,e:
-        print "Exception in actions.py in is_pi %s" % e
+    except Exception as e:
+        logger.error("Exception in actions.py in is_pi {}".format(e))
     return False
     
 # SFA get record
@@ -224,7 +223,7 @@ def sfa_add_authority(request, authority_params):
     # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
     query = Query.create('myslice:authority').set(authority_params).select('authority_hrn')
     results = execute_query(request, query)
-    print "sfa_add_auth results=",results
+    logger.info("sfa_add_auth results={}".format(results))
     if not results:
         raise Exception, "Could not create %s. Already exists ?" % authority_params['hrn']
     return results
@@ -430,7 +429,7 @@ def make_request_authority(authority):
     return request
 
 def make_requests(pending_users, pending_slices, pending_authorities, pending_projects, pending_joins):
-    print "$$$$$$$$$$$$$$$  make_request"
+    logger.info("$$$$$$$$$$$$$$$  make_request")
     requests = []
     for user in pending_users:
         requests.append(make_request_user(user))
@@ -445,7 +444,7 @@ def make_requests(pending_users, pending_slices, pending_authorities, pending_pr
     return requests   
 
 def get_request_by_id(ids):
-    print "$$$$$$$$$$$$$$$$  get_request_by_id"
+    logger.info("$$$$$$$$$$$$$$$$  get_request_by_id")
     sorted_ids = { 'user': [], 'slice': [], 'authority': [], 'project': [], 'join': [] }
     for type__id in ids:
         type, id = type__id.split('__')
@@ -467,7 +466,7 @@ def get_request_by_id(ids):
     return make_requests(pending_users, pending_slices, pending_authorities, pending_projects, pending_joins)
 
 def get_requests(authority_hrns=None):
-    print "$$$$$$$$$$$$$   get_request_by_authority auth_hrns = ", authority_hrns
+    logger.info("$$$$$$$$$$$$$   get_request_by_authority auth_hrns = {}".format(authority_hrns))
     if not authority_hrns:
         ## get those pending users who have confirmed their emails
         pending_users  = PendingUser.objects.filter(status__iexact = 'True')
@@ -574,7 +573,7 @@ def portal_validate_request(wsgi_request, request_ids):
                     #'pi'        : None,
                     #'enabled'    : True
                 }
-                print "ADD Authority"
+                logger.info("ADD Authority")
                 sfa_add_authority(wsgi_request, sfa_authority_params)
                 request_status['SFA authority'] = {'status': True }
                 PendingAuthority.objects.get(id=request['id']).delete()
@@ -629,14 +628,14 @@ def validate_action(request, **kwargs):
     ids = filter(None, kwargs['id'].split('/'))
     status = portal_validate_request(request, ids)
     json_answer = json.dumps(status)
-    return HttpResponse (json_answer, mimetype="application/json")
+    return HttpResponse (json_answer, content_type="application/json")
 
 
 def reject_action(request, **kwargs):
     ids = filter(None, kwargs['id'].split('/'))
     status = portal_reject_request(request, ids)
     json_answer = json.dumps(status)
-    return HttpResponse (json_answer, mimetype="application/json")
+    return HttpResponse (json_answer, content_type="application/json")
 
 
 def portal_reject_request(wsgi_request, request_ids):
@@ -687,8 +686,8 @@ def portal_reject_request(wsgi_request, request_ids):
                     msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
                     msg.attach_alternative(html_content, "text/html")
                     msg.send()
-                except Exception, e:
-                    print "Failed to send email, please check the mail templates and the SMTP configuration of your server"   
+                except Exception as e:
+                    logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")   
 
                 # removing from Django portal_pendinguser
                 PendingUser.objects.get(id=request['id']).delete()
@@ -728,8 +727,8 @@ def portal_reject_request(wsgi_request, request_ids):
                 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
                 msg.attach_alternative(html_content, "text/html")
                 msg.send()
-            except Exception, e:
-                print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+            except Exception as e:
+                logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
                       
             PendingSlice.objects.get(id=request['id']).delete()
 
@@ -767,8 +766,8 @@ def portal_reject_request(wsgi_request, request_ids):
                 msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
                 msg.attach_alternative(html_content, "text/html")
                 msg.send()
-            except Exception, e:
-                print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+            except Exception as e:
+                logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
             PendingAuthority.objects.get(id=request['id']).delete()
 
@@ -866,8 +865,8 @@ def create_slice(wsgi_request, request):
             msg = EmailMultiAlternatives(subject, text_content, sender, [user_email])
             msg.attach_alternative(html_content, "text/html")
             msg.send()
-        except Exception, e:
-            print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+        except Exception as e:
+            logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
        
     return results
 
@@ -904,8 +903,8 @@ def create_pending_slice(wsgi_request, request, email):
         msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
         msg.attach_alternative(html_content, "text/html")
         msg.send()
-    except Exception, e:
-        print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+    except Exception as e:
+        logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
 
 def create_pending_project(wsgi_request, request):
@@ -1061,8 +1060,8 @@ def sfa_create_user(wsgi_request, request, namespace = None, as_admin = False):
             msg = EmailMultiAlternatives(subject, text_content, sender, [request['email']])
             msg.attach_alternative(html_content, "text/html")
             msg.send()
-        except Exception, e:
-            print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+        except Exception as e:
+            logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
     return results
 
@@ -1100,7 +1099,7 @@ def iotlab_create_user (wsgi_request, request, namespace = None, as_admin=False)
    
     iotlab_user_params1 = json.dumps(iotlab_user_params)
     r=requests.post(url=URL_REST, data=iotlab_user_params1, headers=headers, auth=auth)
-    print 'Create iotlab user : ', r.status_code, r.text
+    logger.info('Create iotlab user : {} {}'.format(r.status_code, r.text))
     return r.text
 
 def create_user(wsgi_request, request, namespace = None, as_admin = False):
@@ -1196,8 +1195,8 @@ def create_pending_user(wsgi_request, request, user_detail):
             'config'        : json.dumps(account_config),
         }
         manifold_add_account(wsgi_request, account_params)
-    except Exception, e:
-        print "Failed creating manifold account on platform %s for user: %s" % ('myslice', request['email'])
+    except Exception as e:
+        logger.error("Failed creating manifold account on platform {} for user: {}".format('myslice', request['email']))
 
     try:
         # Send an email: the recipients are the PI of the authority
@@ -1222,6 +1221,6 @@ def create_pending_user(wsgi_request, request, user_detail):
         msg.attach_alternative(html_content, "text/html")
         msg.send()
     except Exception, e:
-        print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+        logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
         import traceback
-        traceback.print_exc()
+        logger.error(traceback.format_exc())
index 0de9b93..4beb7a9 100644 (file)
@@ -11,7 +11,9 @@ from unfold.loginrequired        import LoginRequiredAutoLogoutView
 
 from ui.topmenu                  import topmenu_items_live, the_user
 
-from myslice.theme import ThemeView
+from myslice.theme               import ThemeView
+from myslice.settings            import logger
+
 
 #This view requires login 
 class DashboardView (LoginRequiredAutoLogoutView, ThemeView):
@@ -25,7 +27,7 @@ class DashboardView (LoginRequiredAutoLogoutView, ThemeView):
         #messages.info(self.request, 'You have logged in')
         page = Page(self.request)
 
-        print "Dashboard page"
+        logger.info("Dashboard page")
         # Slow...
         #slice_query = Query().get('slice').filter_by('user.user_hrn', 'contains', user_hrn).select('slice_hrn')
         testbed_query  = Query().get('network').select('network_hrn','platform','version')
@@ -47,8 +49,8 @@ class DashboardView (LoginRequiredAutoLogoutView, ThemeView):
 #            root_authority = sub_authority[0]
 #            slice_query = Query().get(root_authority+':user').filter_by('user_hrn', '==', '$user_hrn').select('user_hrn', 'slice.slice_hrn')
 #        else:
-        print "SLICE QUERY"
-        print "-" * 80
+        logger.debug("SLICE QUERY")
+        logger.debug("-" * 80)
         slice_query = Query().get('myslice:user').filter_by('user_hrn', '==', '$user_hrn').select('slices.slice_hrn')
         page.enqueue_query(slice_query)
         page.enqueue_query(testbed_query)
index 4424c2e..8bb164f 100644 (file)
@@ -1,22 +1,31 @@
-from unfold.loginrequired               import FreeAccessView
-#
-from manifold.core.query                import Query
-from manifoldapi.manifoldapi            import execute_query, execute_admin_query
-from portal.actions                     import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account, sfa_update_user, authority_get_pi_emails, make_request_user, create_user
-#
-from unfold.page                        import Page    
-from ui.topmenu                         import topmenu_items_live, the_user
-#
+import json
+import os
+import re
+import itertools
+
 from django.http                        import HttpResponse, HttpResponseRedirect
 from django.contrib                     import messages
 from django.contrib.auth.decorators     import login_required
-from myslice.theme                      import ThemeView
-from portal.models                      import PendingUser, PendingAuthority
 from django.core.mail                   import EmailMultiAlternatives, send_mail
 from django.contrib.sites.models        import Site
 
-#
-import json, os, re, itertools
+from manifold.core.query                import Query
+from manifoldapi.manifoldapi            import execute_query, execute_admin_query
+
+from unfold.loginrequired               import FreeAccessView
+
+from portal.actions                     import (
+    manifold_update_user, manifold_update_account, manifold_add_account,
+    manifold_delete_account, sfa_update_user, authority_get_pi_emails,
+    make_request_user, create_user)
+from portal.models                      import PendingUser, PendingAuthority
+
+from unfold.page                        import Page    
+from ui.topmenu                         import topmenu_items_live, the_user
+
+from myslice.theme                      import ThemeView
+from myslice.settings                   import logger
+
 
 def ValuesQuerySetToDict(vqs):
     return [item for item in vqs]
@@ -36,8 +45,8 @@ class ActivateEmailView(FreeAccessView, ThemeView):
                 # User is enabled in PLE
                 if 'enabled' in result and result['enabled']==True:
                     return True
-        except Exception, e:
-            print "Exception in myplc query = ",e
+        except Exception as e:
+            logger.error("Exception in myplc query = {}".format(e))
 
         return False
 
@@ -51,7 +60,6 @@ class ActivateEmailView(FreeAccessView, ThemeView):
         #page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css" ] )
 
         for key, value in kwargs.iteritems():
-            #print "%s = %s" % (key, value)
             if key == "hash_code":
                 hash_code=value
         if PendingUser.objects.filter(email_hash__iexact = hash_code).filter(status__iexact = 'False'):           
@@ -100,10 +108,10 @@ class ActivateEmailView(FreeAccessView, ThemeView):
                         #    msg = EmailMultiAlternatives(subject, text_content, sender, recipients)
                         #    msg.attach_alternative(html_content, "text/html")
                         #    msg.send()
-                        #except Exception, e:
-                        #    print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+                        #except Exception as e:
+                        #    logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
                         #    import traceback
-                        #    traceback.print_exc()
+                        #    logger.error(traceback.format_exc())
             
             PendingUser.objects.filter(email_hash__iexact = hash_code).update(status='True')
         else:
index e5087d8..581822c 100644 (file)
@@ -21,8 +21,9 @@
 # this program; see the file COPYING.  If not, write to the Free Software
 # Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 
+# TODO: Remove these automated forms and use html templates and views like any other page !
+
 from django import forms
-from portal.models import PendingUser, PendingSlice
 #from crispy_forms.helper import FormHelper
 #from crispy_forms.layout import Submit
 from django.utils.translation import ugettext_lazy as _
@@ -32,8 +33,12 @@ from django.contrib.sites.models import get_current_site
 from django.utils.http import int_to_base36
 from django.template import loader
 
-# TODO: Remove these automated forms and use html templates and views like any other page !
 from django.contrib.auth.hashers import identify_hasher
+
+from portal.models import PendingUser, PendingSlice
+
+from myslice.settings import logger
+
 # adapted from https://sourcegraph.com/github.com/fusionbox/django-authtools/symbols/python/authtools/forms
 
 def is_password_unusable(pw):
@@ -205,8 +210,8 @@ class PasswordResetForm(forms.Form):
                 subject = ''.join(subject.splitlines())
                 email = loader.render_to_string(email_template_name, c)
                 send_mail(subject, email, from_email, [user.email])
-        except Exception, e:
-            print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+        except Exception as e:
+            logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
 
 
 class SetPasswordForm(forms.Form):
index 1fe1d2a..6d33d0e 100644 (file)
@@ -1,3 +1,6 @@
+import time
+import json
+
 # this somehow is not used anymore - should it not be ?
 from django.core.context_processors     import csrf
 from django.http                        import HttpResponseRedirect
@@ -6,30 +9,28 @@ from django.template                    import RequestContext
 from django.shortcuts                   import render_to_response
 from django.shortcuts                   import render
 
-
 from unfold.loginrequired               import FreeAccessView
+from ui.topmenu                         import topmenu_items, the_user
 
 from manifold.core.query                import Query
 from manifoldapi.manifoldapi            import execute_query
-
 from manifoldapi.manifoldresult         import ManifoldResult
-from ui.topmenu                         import topmenu_items, the_user
-from myslice.configengine               import ConfigEngine
 
+from myslice.configengine               import ConfigEngine
 from myslice.theme                      import ThemeView
+
 from portal.account                     import Account, get_expiration
 from portal.models                      import PendingSlice
 from portal.actions                     import authority_check_pis
 
-import json, time
 import activity.user
 
 class HomeView (FreeAccessView, ThemeView):
     template_name = 'home-view.html'
-        
+
     # expose this so we can mention the backend URL on the welcome page
     def default_env (self):
-        return { 
+        return {
                  'MANIFOLD_URL':ConfigEngine().manifold_url(),
                  }
 
@@ -37,12 +38,12 @@ class HomeView (FreeAccessView, ThemeView):
         env = self.default_env()
         env['theme'] = self.theme
         env['section'] = "Dashboard"
-        
+
         username = request.POST.get('username')
         password = request.POST.get('password')
-        
+
         # pass request within the token, so manifold session key can be attached to the request session.
-        token = {'username': username, 'password': password, 'request': request}    
+        token = {'username': username, 'password': password, 'request': request}
 
         # our authenticate function returns either
         # . a ManifoldResult - when something has gone wrong, like e.g. backend is unreachable
@@ -55,22 +56,21 @@ class HomeView (FreeAccessView, ThemeView):
             manifoldresult = auth_result
             # let's use ManifoldResult.__repr__
             env['state']="%s"%manifoldresult
-            
+
             return render_to_response(self.template,env, context_instance=RequestContext(request))
         # user was authenticated at the backend
         elif auth_result is not None:
             user=auth_result
             if user.is_active:
-                print "LOGGING IN"
                 login(request, user)
-                
-                if request.user.is_authenticated(): 
+
+                if request.user.is_authenticated():
                     env['person'] = self.request.user
                     env['username'] = self.request.user
-                    
+
                     # log user activity
                     activity.user.login(self.request)
-                    
+
                     ## check user is pi or not
                     platform_details = {}
                     account_details = {}
@@ -94,7 +94,7 @@ class HomeView (FreeAccessView, ThemeView):
                     #    pi = "is_not_pi"
                     #else:
                     #    pi = "is_pi"
-                    user_email = str(self.request.user)                   
+                    user_email = str(self.request.user)
                     pi = authority_check_pis(self.request, user_email)
 
                     # check if the user has creds or not
@@ -114,8 +114,8 @@ class HomeView (FreeAccessView, ThemeView):
 
                     env['pending_slices'] = pending_slices
                     env['pi'] = pi
-                    env['user_cred'] = user_cred                
-                else: 
+                    env['user_cred'] = user_cred
+                else:
                     env['person'] = None
                 return render_to_response(self.template,env, context_instance=RequestContext(request))
             else:
@@ -123,21 +123,21 @@ class HomeView (FreeAccessView, ThemeView):
                 activity.user.login(self.request, "notactive")
                 env['state'] = "Your account is not active, please contact the site admin."
                 env['layout_1_or_2']="layout-unfold2.html"
-                
+
                 return render_to_response(self.template,env, context_instance=RequestContext(request))
         # otherwise
         else:
             # log user activity
             activity.user.login(self.request, "error")
             env['state'] = "Your username and/or password were incorrect."
-            
+
             return render_to_response(self.template, env, context_instance=RequestContext(request))
 
     def get (self, request, state=None):
         env = self.default_env()
         acc_auth_cred={}
         if request.user.is_authenticated():
-           
+
             ## check user is pi or not
             platform_details = {}
             account_details = {}
@@ -163,7 +163,7 @@ class HomeView (FreeAccessView, ThemeView):
             #    pi = "is_not_pi"
             #else:
             #    pi = "is_pi"
-            user_email = str(self.request.user) 
+            user_email = str(self.request.user)
             pi = authority_check_pis(self.request, user_email)
             # check if the user has creds or not
             if acc_user_cred == {} or acc_user_cred == 'N/A':
@@ -179,12 +179,12 @@ class HomeView (FreeAccessView, ThemeView):
             pending_slices = []
             for slices in PendingSlice.objects.filter(type_of_nodes__iexact=self.request.user).all():
                 pending_slices.append(slices.slice_name)
-        
+
             env['pending_slices'] = pending_slices
             env['pi'] = pi
-            env['user_cred'] = user_cred                
+            env['user_cred'] = user_cred
             env['person'] = self.request.user
-        else: 
+        else:
             env['person'] = None
 
         env['theme'] = self.theme
@@ -196,7 +196,7 @@ class HomeView (FreeAccessView, ThemeView):
         if state: env['state'] = state
         elif not env['username']: env['state'] = None
         # use one or two columns for the layout - not logged in users will see the login prompt
-        
+
 #         account_query  = Query().get('local:account').select('user_id','platform_id','auth_type','config')
 #         account_details = execute_query(self.request, account_query)
 #         for account_detail in account_details:
@@ -206,17 +206,17 @@ class HomeView (FreeAccessView, ThemeView):
 #                 acc_user_cred = account_config.get('delegated_user_credential','N/A')
 #                 acc_slice_cred = account_config.get('delegated_slice_credentials','N/A')
 #                 acc_auth_cred = account_config.get('delegated_authority_credentials','N/A')
-# 
+#
 #                 if 'N/A' not in acc_user_cred:
 #                     exp_date = re.search('<expires>(.*)</expires>', acc_user_cred)
 #                     if exp_date:
 #                         user_exp_date = exp_date.group(1)
 #                         user_cred_exp_list.append(user_exp_date)
-# 
+#
 #                     my_users = [{'cred_exp': t[0]}
 #                         for t in zip(user_cred_exp_list)]
-#                
-# 
+#
+#
 #                 if 'N/A' not in acc_slice_cred:
 #                     for key, value in acc_slice_cred.iteritems():
 #                         slice_list.append(key)
@@ -225,10 +225,10 @@ class HomeView (FreeAccessView, ThemeView):
 #                         if exp_date:
 #                             exp_date = exp_date.group(1)
 #                             slice_cred_exp_list.append(exp_date)
-# 
+#
 #                     my_slices = [{'slice_name': t[0], 'cred_exp': t[1]}
 #                         for t in zip(slice_list, slice_cred_exp_list)]
-# 
+#
 #                 if 'N/A' not in acc_auth_cred:
 #                     for key, value in acc_auth_cred.iteritems():
 #                         auth_list.append(key)
@@ -238,6 +238,6 @@ class HomeView (FreeAccessView, ThemeView):
 #                             exp_date = exp_date.group(1)
 #                             auth_cred_exp_list.append(exp_date)
 
-        
+
         return render_to_response(self.template, env, context_instance=RequestContext(request))
 
index 8a00435..503a22a 100644 (file)
@@ -1,3 +1,5 @@
+import json
+
 from django.core.context_processors import csrf
 from django.http                    import HttpResponseRedirect
 from django.contrib.auth            import authenticate, login, logout
@@ -16,7 +18,8 @@ from myslice.configengine           import ConfigEngine
 
 from portal.actions                 import is_pi, authority_check_pis
 from myslice.theme                  import ThemeView
-import json
+from myslice.settings               import logger
+
 
 class InstitutionView (LoginRequiredAutoLogoutView, ThemeView):
     template_name = 'institution.html'
@@ -68,9 +71,9 @@ class InstitutionView (LoginRequiredAutoLogoutView, ThemeView):
 
         else: 
             env['person'] = None
-        print "BEFORE  ####------####  is_pi"
+        logger.debug("BEFORE  ####------####  is_pi")
         pi = is_pi(self.request, '$user_hrn', env['user_details']['parent_authority']) 
-        print "is_pi = ",is_pi
+        logger.debug("is_pi = {}".format(is_pi))
 
         env['theme'] = self.theme
         env['section'] = "Institution"
index 2add3a4..6f0d77c 100644 (file)
@@ -22,6 +22,7 @@ from portal.models              import PendingUser,PendingAuthority
 from portal.actions             import authority_get_pi_emails, manifold_add_user,manifold_add_account, create_pending_user
 
 from myslice.theme import ThemeView
+from myslice.settings import logger
 
 import activity.institution
 
@@ -229,9 +230,9 @@ class JoinView (FreeAccessView, ThemeView):
                     msg.send()
     
                 except Exception, e:
-                    print "Failed to send email, please check the mail templates and the SMTP configuration of your server"
+                    logger.error("Failed to send email, please check the mail templates and the SMTP configuration of your server")
                     import traceback
-                    traceback.print_exc()
+                    logger.error(traceback.format_exc())
 
                 self.template_name = 'join_complete.html'
                 # log institution activity
index ec39f8f..02714d4 100644 (file)
@@ -1,3 +1,4 @@
+import json
 # this somehow is not used anymore - should it not be ?
 from django.core.context_processors import csrf
 from django.http import HttpResponseRedirect
@@ -11,10 +12,10 @@ from unfold.loginrequired import FreeAccessView
 from manifold.core.query            import Query
 from manifoldapi.manifoldapi        import execute_query
 from manifoldapi.manifoldresult import ManifoldResult
-from myslice.configengine import ConfigEngine
 
+from myslice.configengine import ConfigEngine
 from myslice.theme import ThemeView
-import json
+from myslice.settings import logger
 
 class ManagementAboutView (FreeAccessView, ThemeView):
     template_name = 'management-tab-about.html'
@@ -27,7 +28,7 @@ class ManagementAboutView (FreeAccessView, ThemeView):
             user_local_query  = Query().get('local:user').select('config').filter_by('email','==',str(self.request.user))
             user_local_details = execute_query(self.request, user_local_query)
             user_authority = json.loads(user_local_details[0]['config']).get('authority')
-            print "**************________    management about  = ",user_authority
+            logger.info("**************________    management about  = {}".format(user_authority))
             # XXX Should be done using Metadata
             # select column.name from local:object where table=='authority'
             authority_query = Query().get('authority').select('authority_hrn', 'name', 'address', 'enabled','description', 
index 2c80e41..2d1cdef 100644 (file)
@@ -1,3 +1,5 @@
+import json
+
 from django.template                 import RequestContext
 from django.shortcuts                import render_to_response
 
@@ -18,8 +20,7 @@ from manifoldapi.manifoldapi        import execute_query
 from portal.actions                 import get_requests
 
 from myslice.theme import ThemeView
-
-import json
+from myslice.settings import logger
 
 class ManagementRequestsView (LoginRequiredView, ThemeView):
     template_name = "management-tab-requests.html"
@@ -47,7 +48,7 @@ class ManagementRequestsView (LoginRequiredView, ThemeView):
             sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
             sfa_platforms = execute_query(self.request, sfa_platforms_query)
             for sfa_platform in sfa_platforms:
-                print "SFA PLATFORM > ", sfa_platform['platform']
+                logger.info("SFA PLATFORM > {}".format(sfa_platform['platform']))
                 if not 'auth_type' in sfa_platform:
                     continue
                 auth = sfa_platform['auth_type']
@@ -55,7 +56,7 @@ class ManagementRequestsView (LoginRequiredView, ThemeView):
                     all_authorities.append(auth)
                 platform_ids.append(sfa_platform['platform_id'])
 
-            print "W: Hardcoding platform myslice"
+            logger.warning("W: Hardcoding platform myslice")
             # There has been a tweak on how new platforms are referencing a
             # so-called 'myslice' platform for storing authentication tokens.
             # XXX This has to be removed in final versions.
@@ -101,8 +102,8 @@ class ManagementRequestsView (LoginRequiredView, ThemeView):
             try:
                 for pa in pi_authorities_tmp:
                     pi_authorities |= set(pa['pi_authorities'])
-            except:
-                print 'No pi_authorities'
+            except Exception as e:
+                logger.error('No pi_authorities')
 
             pi_credential_authorities = pi_authorities & credential_authorities
             pi_no_credential_authorities = pi_authorities - credential_authorities - credential_authorities_expired
index 1be4e82..47e6974 100644 (file)
@@ -1,19 +1,24 @@
+import os
+import re
+import itertools
+import json
+
 from unfold.loginrequired               import LoginRequiredAutoLogoutView
-#
+
 from manifold.core.query                import Query
 from manifoldapi.manifoldapi            import execute_query, execute_admin_query
 from portal.actions                     import manifold_update_user, manifold_update_account, manifold_add_account, manifold_delete_account
-from portal.actions                     import sfa_update_user, authority_get_pis, authority_add_pis, authority_remove_pis,authority_check_pis ,clear_user_creds
-#
+from portal.actions                     import (
+    sfa_update_user, authority_get_pis, authority_add_pis,
+    authority_remove_pis,authority_check_pis ,clear_user_creds )
+
 from unfold.page                        import Page    
 from ui.topmenu                         import topmenu_items_live, the_user
-#
+
 from django.http                        import HttpResponse, HttpResponseRedirect
 from django.contrib                     import messages
 from django.contrib.auth.decorators     import login_required
 from myslice.theme import ThemeView
-#
-import json, os, re, itertools
 
 # requires login
 class UserView(LoginRequiredAutoLogoutView, ThemeView):
@@ -29,7 +34,6 @@ class UserView(LoginRequiredAutoLogoutView, ThemeView):
         page.add_css_files ( [ "css/onelab.css", "css/account_view.css","css/plugin.css","css/jquery-ui.css" ] )
 
         for key, value in kwargs.iteritems():
-            #print "%s = %s" % (key, value)
             if key == "email":
                 selected_email=value
     
index f578d93..9ffff60 100644 (file)
@@ -33,11 +33,11 @@ from django.template.loader   import render_to_string
 
 #from django.core.validators import validate_email
 
-try:
-    from django.contrib.auth import get_user_model
-    User = get_user_model()
-except ImportError:
-    from django.contrib.auth.models import User
+#try:
+#    from django.contrib.auth import get_user_model
+#    User = get_user_model()
+#except ImportError:
+#    from django.contrib.auth.models import User
 
 try:
     from django.utils.timezone import now as datetime_now
diff --git a/portal/native_migrations/0001_initial.py b/portal/native_migrations/0001_initial.py
new file mode 100644 (file)
index 0000000..d307a59
--- /dev/null
@@ -0,0 +1,114 @@
+# -*- coding: utf-8 -*-
+from __future__ import unicode_literals
+
+from django.db import models, migrations
+
+
+class Migration(migrations.Migration):
+
+    dependencies = [
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name='Institution',
+            fields=[
+                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+                ('name', models.TextField()),
+            ],
+            options={
+            },
+            bases=(models.Model,),
+        ),
+        migrations.CreateModel(
+            name='PendingAuthority',
+            fields=[
+                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+                ('site_name', models.TextField()),
+                ('site_authority', models.TextField()),
+                ('site_abbreviated_name', models.TextField()),
+                ('site_url', models.TextField()),
+                ('site_latitude', models.TextField()),
+                ('site_longitude', models.TextField()),
+                ('address_line1', models.TextField()),
+                ('address_line2', models.TextField()),
+                ('address_line3', models.TextField()),
+                ('address_city', models.TextField()),
+                ('address_postalcode', models.TextField()),
+                ('address_state', models.TextField()),
+                ('address_country', models.TextField()),
+                ('authority_hrn', models.TextField()),
+                ('created', models.DateTimeField(auto_now_add=True)),
+            ],
+            options={
+            },
+            bases=(models.Model,),
+        ),
+        migrations.CreateModel(
+            name='PendingJoin',
+            fields=[
+                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+                ('user_hrn', models.TextField()),
+                ('email', models.TextField()),
+                ('project_name', models.TextField(null=True)),
+                ('authority_hrn', models.TextField()),
+                ('created', models.DateTimeField(auto_now_add=True)),
+            ],
+            options={
+            },
+            bases=(models.Model,),
+        ),
+        migrations.CreateModel(
+            name='PendingProject',
+            fields=[
+                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+                ('project_name', models.TextField()),
+                ('user_hrn', models.TextField()),
+                ('email', models.TextField()),
+                ('authority_hrn', models.TextField(null=True)),
+                ('purpose', models.TextField(default=b'NA')),
+                ('created', models.DateTimeField(auto_now_add=True)),
+            ],
+            options={
+            },
+            bases=(models.Model,),
+        ),
+        migrations.CreateModel(
+            name='PendingSlice',
+            fields=[
+                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+                ('slice_name', models.TextField()),
+                ('user_hrn', models.TextField()),
+                ('authority_hrn', models.TextField(null=True)),
+                ('number_of_nodes', models.TextField(default=0)),
+                ('type_of_nodes', models.TextField(default=b'NA')),
+                ('purpose', models.TextField(default=b'NA')),
+                ('created', models.DateTimeField(auto_now_add=True)),
+            ],
+            options={
+            },
+            bases=(models.Model,),
+        ),
+        migrations.CreateModel(
+            name='PendingUser',
+            fields=[
+                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
+                ('first_name', models.TextField()),
+                ('last_name', models.TextField()),
+                ('email', models.EmailField(max_length=75)),
+                ('password', models.TextField()),
+                ('user_hrn', models.TextField()),
+                ('public_key', models.TextField()),
+                ('private_key', models.TextField()),
+                ('authority_hrn', models.TextField()),
+                ('login', models.TextField()),
+                ('pi', models.TextField()),
+                ('email_hash', models.TextField()),
+                ('status', models.TextField()),
+                ('created', models.DateTimeField(auto_now_add=True)),
+            ],
+            options={
+            },
+            bases=(models.Model,),
+        ),
+    ]
diff --git a/portal/native_migrations/__init__.py b/portal/native_migrations/__init__.py
new file mode 100644 (file)
index 0000000..e69de29
index b0fc3ec..ec5454d 100644 (file)
@@ -16,6 +16,7 @@ from plugins.querytable          import QueryTable
 
 from myslice.configengine        import ConfigEngine
 from myslice.theme import ThemeView
+from myslice.settings import logger
 
 # View for 1 platform and its details
 class PlatformView(FreeAccessView, ThemeView):
@@ -26,7 +27,7 @@ class PlatformView(FreeAccessView, ThemeView):
         page.add_js_files  ( [ "js/common.functions.js" ] )
 
         for key, value in kwargs.iteritems():
-            print "%s = %s" % (key, value)       
+            logger.debug("{} = {}".format(key, value))
             if key == "platformname":
                 platformname=value
                 
index 8a48428..a505f14 100644 (file)
@@ -1,3 +1,7 @@
+import json
+import time
+import re
+
 from django.shortcuts           import render
 from django.contrib.sites.models import Site
 
@@ -10,8 +14,7 @@ from portal.actions import create_pending_project, create_pending_join, sfa_add_
 from portal.models import PendingProject, PendingJoin
 
 from myslice.theme import ThemeView
-
-import json, time, re
+from myslice.settings import logger
 
 class ProjectRequestView(LoginRequiredAutoLogoutView, ThemeView):
     template_name = 'projectrequest_view.html'
@@ -119,7 +122,7 @@ class ProjectRequestView(LoginRequiredAutoLogoutView, ThemeView):
                 errors.append('Project name is mandatory')
             
             if not errors:
-                print "is_pi on auth_hrn = ", user_authority
+                logger.info("is_pi on auth_hrn = {}".format(user_authority))
                 if is_pi(wsgi_request, user_hrn, user_authority):
                     # PIs can directly create/join project in their own authority...
                     if 'join' in wsgi_request.POST:
index 2ce1efa..9032125 100644 (file)
@@ -1,4 +1,5 @@
-import os.path, re
+import os.path
+import re
 import json
 from random     import randint
 from hashlib    import md5
@@ -21,6 +22,7 @@ from portal.models              import PendingUser
 from portal.actions             import create_pending_user
 
 from myslice.theme import ThemeView
+from myslice.settings import logger
 
 import activity.user
 
@@ -44,14 +46,14 @@ class RegistrationView (FreeAccessView, ThemeView):
         # REGISTRY ONLY TO BE REMOVED WITH MANIFOLD-V2
         authorities_query = Query.get('authority').select('name', 'authority_hrn')
         authorities = execute_admin_query(wsgi_request, authorities_query)
-        print "RegistrationView authorities = ", authorities
+        logger.info("RegistrationView authorities = {}".format(authorities))
         if authorities is not None:
             # Remove the root authority from the list
             matching = [s for s in authorities if "." in s['authority_hrn']]
             authorities = sorted(matching, key=lambda k: k['authority_hrn'])
             authorities = sorted(matching, key=lambda k: k['name'])
         
-        print "############ BREAKPOINT 1 #################"
+        logger.debug("############ BREAKPOINT 1 #################")
         # Page rendering
         page = Page(wsgi_request)
 
@@ -61,7 +63,7 @@ class RegistrationView (FreeAccessView, ThemeView):
 
         page.add_css_files ( [ "css/onelab.css", "css/registration.css", "css/jquery.qtip.min.css", "css/jquery.ui.combobox.css" ] )
         page.expose_js_metadata()
-        print "############ BREAKPOINT 2 #################"
+        logger.debug("############ BREAKPOINT 2 #################")
         if method == 'POST':
             reg_form = {}
             # The form has been submitted
@@ -70,7 +72,7 @@ class RegistrationView (FreeAccessView, ThemeView):
             current_site = Site.objects.get_current()
             current_site = current_site.domain
            
-            print "############ BREAKPOINT 3 #################"
+            logger.debug("############ BREAKPOINT 3 #################")
             post_email = wsgi_request.POST.get('email','').lower()
             salt = randint(1,100000)
             email_hash = md5(str(salt)+post_email).hexdigest()
@@ -87,13 +89,13 @@ class RegistrationView (FreeAccessView, ThemeView):
                 'validation_link': current_site + '/portal/email_activation/'+ email_hash
             }
 
-            print "############ BREAKPOINT 4 #################"
+            logger.debug("############ BREAKPOINT 4 #################")
             auth = wsgi_request.POST.get('org_name', None)
             if auth is None or auth == "":
                 errors.append('Organization required: please select one or request its addition')
             else:
                
-                print "############ BREAKPOINT 5 #################"
+                logger.debug("############ BREAKPOINT 5 #################")
                 
                 # Construct user_hrn from email (XXX Should use common code)
                 split_email = user_request['email'].split("@")[0] 
@@ -183,7 +185,7 @@ class RegistrationView (FreeAccessView, ThemeView):
                     return render(wsgi_request, self.template, {'theme': self.theme}) 
 
         else:
-            print "############ BREAKPOINT A #################"
+            logger.debug("############ BREAKPOINT A #################")
             user_request = {}
             ## this is coming from onelab website onelab.eu
             reg_form = {
@@ -193,7 +195,7 @@ class RegistrationView (FreeAccessView, ThemeView):
                 }
             # log user activity
             activity.user.signup(self.request)
-            print "############ BREAKPOINT B #################"
+            logger.debug("############ BREAKPOINT B #################")
 
         template_env = {
           #'topmenu_items': topmenu_items_live('Register', page),
@@ -204,5 +206,5 @@ class RegistrationView (FreeAccessView, ThemeView):
         template_env.update(user_request)
         template_env.update(reg_form)
         template_env.update(page.prelude_env ())
-        print "############ BREAKPOINT C #################"
+        logger.debug("############ BREAKPOINT C #################")
         return render(wsgi_request, self.template,template_env)
index fcc5ff0..a08ad46 100644 (file)
@@ -22,7 +22,7 @@ from django.views.decorators.csrf import csrf_exempt
 from django.http                  import *
 
 
-def response_mimetype(request):
+def response_content_type(request):
         
     if "application/json" in request.META['HTTP_ACCEPT']:
         return "application/json"
@@ -233,7 +233,7 @@ class ReputationView (LoginRequiredAutoLogoutView, ThemeView):
             
             slicedata_received = json_to_rest('http://survivor.lab.netmode.ntua.gr:4567/reputation/json', dict_to_send )
                         
-            return HttpResponse(json.dumps(slicedata_received), content_type = response_mimetype(self.request))
+            return HttpResponse(json.dumps(slicedata_received), content_type = response_content_type(self.request))
 
                 
         slices_users = []
@@ -376,4 +376,4 @@ class ReputationView (LoginRequiredAutoLogoutView, ThemeView):
                     
                     
                     
-            
\ No newline at end of file
+            
index d670645..1d3b9af 100644 (file)
@@ -22,7 +22,6 @@ class ResourceView(FreeAccessView, ThemeView):
         page.add_js_files  ( [ "js/common.functions.js" ] )
 
         for key, value in kwargs.iteritems():
-            print "%s = %s" % (key, value)       
             if key == "urn":
                 resource_urn=value
                 
index a880d39..b7be0a8 100644 (file)
@@ -1,7 +1,10 @@
+import json
+import time
+import re
+
 from django.shortcuts           import render
 from django.contrib.sites.models import Site
 
-
 from unfold.page                import Page
 
 from manifold.core.query        import Query
@@ -13,8 +16,7 @@ from unfold.loginrequired       import LoginRequiredAutoLogoutView
 from ui.topmenu                 import topmenu_items_live, the_user
 
 from myslice.theme import ThemeView
-
-import json, time, re
+from myslice.settings import logger
 
 import activity.user
 
@@ -87,7 +89,7 @@ class SliceRequestView (LoginRequiredAutoLogoutView, ThemeView):
         #    pi = "is_pi"
 
         pi = authority_check_pis (wsgi_request, user_email)
-        print "SLICEREQUESTVIEW.PY -----  pi=",pi
+        logger.debug("SLICEREQUESTVIEW.PY -----  pi= {}".format(pi))
 
         # Page rendering
         page = Page(wsgi_request)
index c394345..8bdc6e6 100644 (file)
@@ -1,16 +1,16 @@
+import json
+
 from django.template                    import RequestContext
 from django.shortcuts                   import render_to_response
+from django.views.generic.base          import TemplateView
+from django.http import HttpResponse
+from django.shortcuts import render
 
 from manifold.core.query                import Query, AnalyzedQuery
 from manifoldapi.manifoldapi            import execute_query
-import json
 
-from django.views.generic.base          import TemplateView
 
 from unfold.loginrequired               import LoginRequiredView
-from django.http import HttpResponse
-from django.shortcuts import render
-
 from unfold.page                        import Page
 
 from myslice.configengine               import ConfigEngine
@@ -30,7 +30,7 @@ from plugins.univbrisfv                 import UnivbrisFv
 from plugins.univbrisfvf                import UnivbrisFvf
 from plugins.univbrisfvfo              import UnivbrisFvfo
 from plugins.univbristopo               import UnivbrisTopo
-from plugins.univbrisvtam                  import UnivbrisVtam as UnivbrisVtamPlugin
+from plugins.univbrisvtam               import UnivbrisVtam as UnivbrisVtamPlugin
 from plugins.univbrisvtamform          import UnivbrisVtamForm
 
 from plugins.columns_editor             import ColumnsEditor
@@ -38,6 +38,7 @@ from plugins.sladialog                  import SlaDialog
 from plugins.lists.simplelist           import SimpleList
 
 from myslice.theme import ThemeView
+from myslice.settings import logger
 
 class SliceResourceView (LoginRequiredView, ThemeView):
     template_name = "slice-resource-view.html"
@@ -71,7 +72,7 @@ class SliceResourceView (LoginRequiredView, ThemeView):
 
         slice_md = metadata.details_by_object('slice')
         slice_fields = [column['name'] for column in slice_md['column']]
-        print "SLICE RES VIEW fields = %s" % slice_fields
+        logger.debug("SLICE RES VIEW fields = {}".format(slice_fields))
         # TODO The query to run is embedded in the URL
         # Example: select slice_hrn, resource.urn, lease.resource, lease.start_time, lease.end_time from slice where slice_hrn == "ple.upmc.myslicedemo"
         main_query = Query.get('slice').filter_by('slice_hrn', '=', slicename)
index ab2fee2..138754a 100644 (file)
@@ -16,6 +16,7 @@ from myslice.configengine import ConfigEngine
 
 from myslice.theme import ThemeView
 from myslice.configengine import ConfigEngine
+from myslice.settings import logger
 
 from sfa.planetlab.plxrn import hash_loginbase
 
@@ -43,12 +44,8 @@ class ExperimentView (FreeAccessView, ThemeView):
         try:
             for resources in current_resources:
                 list_res = resources['resource']
-                #print "list_b4"
-                #print list_res
                 for res in list_res:
                     split_list = res.split('+') # split the resource urn
-                    #print "list_after"
-                    #print split_list
                     if [s for s in split_list if 'ple' in s]: # find ple resources
                         res_hrn = split_list[-1] # last element is resource hrn
                         ple_resource_list.append(res_hrn)
@@ -66,17 +63,17 @@ class ExperimentView (FreeAccessView, ThemeView):
                         nitos_resource_list.append(res_hrn)
 
 
-        except Exception,e:
-            print "Exception in slicetabexperiment.py in OneLab resource search %s" % e
+        except Exception as e:
+            logger.error("Exception in slicetabexperiment.py in OneLab resource search {}".format(e))
         
-        #print "list of ple res hrns"
-        #print ple_resource_list
-        #print "list of nit_paris res hrns"
-        #print nitos_paris_resource_list
-        #print "list of iotLab res hrns"
-        #print iotlab_resource_list
-        #print "list of nitos res hrns"
-        #print nitos_resource_list
+        #logger.debug("list of ple res hrns")
+        #logger.debug(ple_resource_list)
+        #logger.debug("list of nit_paris res hrns")
+        #logger.debug(nitos_paris_resource_list)
+        #logger.debug("list of iotLab res hrns")
+        #logger.debug(iotlab_resource_list)
+        #logger.debug("list of nitos res hrns")
+        #logger.debug(nitos_resource_list)
 
         all_users = list() 
         #get all  iotlab users
@@ -92,7 +89,7 @@ class ExperimentView (FreeAccessView, ThemeView):
             res = urllib2.urlopen(req)
             all_users = json.load(res) 
         except urllib2.URLError as e:
-            print "There is a problem in getting iotlab users %s" % e.reason
+            logger.error("There is a problem in getting iotlab users {}".format(e.reason))
        
 
         #getting the login from email
index 7154b8a..40b7521 100644 (file)
@@ -30,7 +30,6 @@ class UnivbrisView (LoginRequiredAutoLogoutView):
     def get_context_data(self, **kwargs):
         
         page = Page(self.request)
-        #print "UNIVBRIS page"
         metadata = page.get_metadata()
         page.expose_js_metadata()
     
index b87a250..8c9d210 100644 (file)
@@ -44,7 +44,9 @@ from portal.actions             import get_requests
 from manifoldapi.manifoldapi    import execute_query
 from manifold.core.query        import Query
 from unfold.page                import Page
+
 from myslice.theme import ThemeView
+from myslice.settings import logger
 
 class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
     template_name = "validate_pending.html"
@@ -90,7 +92,7 @@ class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
             sfa_platforms_query = Query().get('local:platform').filter_by('gateway_type', '==', 'sfa').select('platform_id', 'platform', 'auth_type')
             sfa_platforms = execute_query(self.request, sfa_platforms_query)
             for sfa_platform in sfa_platforms:
-                print "SFA PLATFORM > ", sfa_platform['platform']
+                logger.info("SFA PLATFORM > {}".format(sfa_platform['platform']))
                 if not 'auth_type' in sfa_platform:
                     continue
                 auth = sfa_platform['auth_type']
@@ -98,7 +100,7 @@ class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
                     all_authorities.append(auth)
                 platform_ids.append(sfa_platform['platform_id'])
 
-            print "W: Hardcoding platform myslice"
+            logger.warning("W: Hardcoding platform myslice")
             # There has been a tweak on how new platforms are referencing a
             # so-called 'myslice' platform for storing authentication tokens.
             # XXX This has to be removed in final versions.
@@ -120,30 +122,30 @@ class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
             #print "=" * 80
             for user_account in user_accounts:
 
-                print "USER ACCOUNT", user_account
+                logger.debug("USER ACCOUNT {}".format(user_account))
                 if user_account['auth_type'] == 'reference':
                     continue # we hardcoded the myslice platform...
 
                 config = json.loads(user_account['config'])
                 creds = []
-                print "CONFIG KEYS", config.keys()
+                logger.debug("CONFIG KEYS {}".format(config.keys()))
                 if 'authority_credentials' in config:
-                    print "***", config['authority_credentials'].keys()
+                    logger.debug("*** AC {}".format(config['authority_credentials'].keys()))
                     for authority_hrn, credential in config['authority_credentials'].items():
                         #if credential is not expired:
                         credential_authorities.add(authority_hrn)
                         #else
                         #    credential_authorities_expired.add(authority_hrn)
                 if 'delegated_authority_credentials' in config:
-                    print "***", config['delegated_authority_credentials'].keys()
+                    logger.debug("*** DAC {}".format(config['delegated_authority_credentials'].keys()))
                     for authority_hrn, credential in config['delegated_authority_credentials'].items():
                         #if credential is not expired:
                         credential_authorities.add(authority_hrn)
                         #else
                         #    credential_authorities_expired.add(authority_hrn)
 
-            print 'credential_authorities =', credential_authorities
-            print 'credential_authorities_expired =', credential_authorities_expired
+            logger.debug('credential_authorities = {}'.format(credential_authorities))
+            logger.debug('credential_authorities_expired = {}'.format(credential_authorities_expired))
 
 #            # Using cache manifold-tables to get the list of authorities faster
 #            all_authorities_query = Query.get('authority').select('name', 'authority_hrn')
@@ -157,8 +159,8 @@ class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
             try:
                 for pa in pi_authorities_tmp:
                     pi_authorities |= set(pa['pi_authorities'])
-            except:
-                print 'No pi_authorities'
+            except Exception as e:
+                logger.error('No pi_authorities')
 # TODO: exception if no parent_authority
 #             try:
 #                 for pa in pi_authorities_tmp:
@@ -260,8 +262,8 @@ class ValidatePendingView(LoginRequiredAutoLogoutView, ThemeView):
                 dest[auth_hrn].append(request)
         
         context = super(ValidatePendingView, self).get_context_data(**kwargs)
-        print "testing"
-        print ctx_my_authorities
+        logger.debug("testing")
+        logger.debug(ctx_my_authorities)
         context['my_authorities']   = ctx_my_authorities
         context['sub_authorities']   = ctx_sub_authorities
         context['delegation_authorities'] = ctx_delegation_authorities
index d58593c..7ed4e08 100644 (file)
@@ -139,7 +139,7 @@ def pres_view_methods(request, type):
         config.close()
     else:
         return 0
-    return HttpResponse (json_answer, mimetype="application/json")
+    return HttpResponse (json_answer, content_type="application/json")
 
 def pres_view_animation(request, constraints, id):
 
@@ -184,7 +184,7 @@ def pres_view_animation(request, constraints, id):
     }]
 
     json_answer = json.dumps(cmd)
-    return HttpResponse (json_answer, mimetype="application/json")
+    return HttpResponse (json_answer, content_type="application/json")
 
 def pres_view_static(request, constraints, id):
     #constraints = "']date_created':1262325600"
@@ -221,4 +221,4 @@ def pres_view_static(request, constraints, id):
     }]
 
     json_answer = json.dumps(cmd)
-    return HttpResponse (json_answer, mimetype="application/json")
+    return HttpResponse (json_answer, content_type="application/json")
index c348483..65ff7e6 100644 (file)
@@ -1,13 +1,15 @@
-from manifold.core.query            import Query
-from manifoldapi.manifoldapi        import execute_query
-from portal.actions                 import is_pi
+import decimal
+import datetime
+import json
 
 from django.http                    import HttpResponse
 
+from manifold.core.query            import Query
+from manifoldapi.manifoldapi        import execute_query
 
-import decimal
-import datetime
-import json
+from portal.actions                 import is_pi
+
+from myslice.settings               import logger
 
 # handles serialization of datetime in json
 DateEncoder = lambda obj: obj.strftime("%B %d, %Y %H:%M:%S") if isinstance(obj, datetime.datetime) else None
@@ -75,7 +77,7 @@ class ObjectRequest(object):
         # What about key formed of multiple fields???
         query = Query.get('local:object').filter_by('table', '==', self.type).select('key')
         results = execute_query(self.request, query)
-        print "key of object = %s" % results
+        logger.debug("key of object = {}".format(results))
         if results :
             for r in results[0]['key'] :
                 self.id = r
@@ -136,9 +138,9 @@ class ObjectRequest(object):
         if self.params :
             for p in self.params :
                 for k,v in p.iteritems() :
-                    print "param: %s : %s" % (k,v)
+                    logger.debug("param: {} : {}".format(k, v))
                     query.set({k : v})
-            print "query = ",query
+            logger.debug("query = {}".format(query))
         else:
             raise Exception, "Params are required for create"
         return execute_query(self.request, query)
@@ -150,9 +152,9 @@ class ObjectRequest(object):
         if self.params :
             for p in self.params :
                 for k,v in p.iteritems() :
-                    print "param: %s : %s" % (k,v)
+                    logger.debug("param: {} : {}".format(k, v))
                     query.set({k : v})
-            print "query = ",query
+            logger.debug("query = {}".format(query))
         else:
             raise Exception, "Params are required for update"
 
index afb62b7..e3b8e4d 100644 (file)
@@ -23,8 +23,7 @@ def dispatch(request, object_type, object_name):
     elif request.method == 'GET':
         #return error('only post request is supported')
         req_items = request.GET
-    print req_items
-    for el in req_items.items():
+    for el in list(req_items.items()):
         # Filters not used for create
         if el[0].startswith('filters'):
             o.filters[el[0][8:-1]] = el[1]
@@ -44,6 +43,6 @@ def dispatch(request, object_type, object_name):
         else :
             return error('an error has occurred')
  
-    except Exception, e:
+    except Exception as e:
         return error(str(e))
 
index 21e9087..02c651b 100644 (file)
@@ -19,7 +19,6 @@ def dispatch(request, object_type, object_name):
         if el[0].startswith('filters'):
             o.filters[el[0][8:-1]] = el[1]
         elif el[0].startswith('fields'):
-            print req_items.getlist('fields[]')
             o.setFields(req_items.getlist('fields[]'))
         elif el[0].startswith('options'):
             o.options = req_items.getlist('options[]')
index 41dbc9b..fd2c317 100644 (file)
@@ -46,7 +46,6 @@ def dispatch(request, action):
                 error = "Error in delete return value"
     except Exception, e:
         error = str(e)
-        #print "Exception : ",e
     if error is not None:
         ret = { "ret" : 1, "error" : error }
     elif not results :
index 04b156b..800429a 100644 (file)
@@ -1,25 +1,23 @@
+import os
+import json
+import ConfigParser 
+
+from django.shortcuts           import render_to_response
+from django.http import HttpResponse
+
 from sfa.trust.certificate      import Keypair, Certificate
 from sfa.client.sfaserverproxy  import SfaServerProxy
 from sfa.client.return_value    import ReturnValue
 from sfa.util.xrn               import Xrn, get_leaf, get_authority, hrn_to_urn, urn_to_hrn
+
 from manifold.core.query        import Query
 from manifold.models            import db
 from manifold.models.platform   import Platform
 from manifold.models.user       import User
 
-from django.shortcuts           import render_to_response
-
 from unfold.loginrequired       import LoginRequiredView
 
-from rest import ObjectRequest, error
-
-from string import join
-
-from django.http import HttpResponse
-from rest import error
-import os,json
-
-import ConfigParser 
+from myslice.settings import logger
 
 def dispatch(request, method):
     Config = ConfigParser.ConfigParser()
@@ -58,15 +56,15 @@ def dispatch(request, method):
     from manifoldapi.manifoldapi    import execute_admin_query
     for pf in platforms:
         platform = get_platform_config(pf)
-        print platform
+        logger.debug("platform={}".format(platform))
         if 'sm' in platform and len(platform['sm']) > 0:
-            print 'sm'
+            logger.debug('sm')
             server_url = platform['sm']
         if 'rm' in platform and len(platform['rm']) > 0:
-            print 'rm'
+            logger.debug('rm')
             server_url = platform['rm']
         if 'registry' in platform and len(platform['registry']) > 0:
-            print 'registry'
+            logger.debug('registry')
             server_url = platform['registry']
     
         if not Config.has_option('monitor', 'cert') :
index 8deb428..fdd9578 100644 (file)
@@ -1,18 +1,15 @@
+from rest import ObjectRequest, error, success
+
 from django.views.generic.base      import TemplateView
 from django.shortcuts               import render_to_response
+from django.http                    import HttpResponse
 
 from unfold.loginrequired           import LoginRequiredView
-from django.http                    import HttpResponse
 
 from manifold.core.query            import Query, AnalyzedQuery
 from manifoldapi.manifoldapi        import execute_query
 
-from rest import ObjectRequest, error, success
-
-from string import join
-
-import json
-
+from myslice.settings import logger
 
 def dispatch(request, object_type, object_name):
     
@@ -23,15 +20,15 @@ def dispatch(request, object_type, object_name):
     elif request.method == 'GET':
         #return error('only post request is supported')
         req_items = request.GET
-    print req_items
+    logger.debug(req_items)
     for el in req_items.items():
         
-        print "#===============>",el
+        logger.debug("#===============> {}".format(el))
         if el[0].startswith('filters'):
             o.filters[el[0][8:-1]] = el[1]
         elif el[0].startswith('params'):
-            print "#======> 0 ", el[0]
-            print "#======> 1 ", req_items.getlist(el[0])
+            logger.debug("#======> 0 {}".format(el[0]))
+            logger.debug("#======> 1 {}".format(req_items.getlist(el[0])))
 
             if (el[0][-2:] == '[]') :
                 # when receiving params[key][] = 'value1' ...
@@ -41,7 +38,7 @@ def dispatch(request, object_type, object_name):
                 # when receiving params[key] = 'value'
                 o.params.append({el[0][7:-1]:el[1]})
             
-            print "o.params = ",o.params
+            logger.debug("o.params = {}".format(o.params))
             
         elif el[0].startswith('fields'):
             o.fields=req_items.getlist('fields[]')
index 641e491..53e0782 100644 (file)
@@ -9,10 +9,12 @@ from ui.topmenu import topmenu_items, the_user
 # tmp
 from trashutils import lorem, hard_wired_slice_names
 
+from myslice.settings import logger
+
 @login_required
 def tab_view (request):
-    print "request", request.__class__
-    print request
+    logger.info("request {}".format(request.__class__))
+    logger.info("{}".format(request))
     prelude=Prelude( js_files='js/bootstrap.js', css_files='css/bootstrap.css')
 
     tab_env = {'title':'Page for playing with Tabs',
index 506423c..e14efb8 100644 (file)
@@ -9,6 +9,8 @@ from unfold.page import Page
 
 from ui.topmenu import topmenu_items_live, the_user
 
+from myslice.settings import logger
+
 class TopmenuValidationView (TemplateView):
 
     # mention a user name in the URL as .../trash/simpletopmenuvalidation/ple.inria.thierry_parmentelat
@@ -35,9 +37,9 @@ class TopmenuValidationView (TemplateView):
         # define {js,css}_{files,chunks}
         prelude_env = page.prelude_env()
 
-#        print prelude_env.keys()
+#        logger.info(prelude_env.keys())
 #        for k in [ 'js_files' ] :
-#            print 'prelude_env',prelude_env,k,prelude_env[k]
+#            logger.info('prelude_env {} {} {}'.format(prelude_env,k,prelude_env[k]))
 
         template_env.update(prelude_env)
         result=render_to_response ('view-unfold1.html',template_env,
index 667711d..0b022b5 100644 (file)
@@ -1,5 +1,7 @@
 # a set of utilities to help make the global layout consistent across views
 
+from myslice.settings import logger
+
 def the_user (request):
     "retrieves logged in user's email, or empty string"
     if not request.user.is_authenticated (): 
@@ -22,7 +24,7 @@ def the_user (request):
 def topmenu_items_static (current, request):
     has_user=request.user.is_authenticated()
     result=[]
-    print request.user
+    logger.debug("request user = {}".format(request.user))
     if has_user:
         result.append({'label':'Dashboard', 'href': '/portal/dashboard/'})
         result.append({'label':'Request a slice', 'href': '/portal/slice_request/'})
@@ -58,7 +60,7 @@ def topmenu_items_static (current, request):
 
 # tmp - transition phase
 def topmenu_items (current, request):
-    print "WARNING -- please now use topmenu_items_live (label, page) toplevel_items is deprecated -- WARNING"
+    logger.warning("WARNING -- please now use topmenu_items_live (label, page) toplevel_items is deprecated -- WARNING")
     return topmenu_items_static (current, request)
 
 # integrated helper function for an animated menu
index 0c6a1d2..bee1fe4 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
 import os
 from django.conf import settings
 from django.utils.datastructures import SortedDict
@@ -79,7 +81,7 @@ class ThirdPartyFinder(BaseFinder):
                         matched_path = os.path.join(path, file) 
                         if not all:
                             return matched_path
-                        print 'ThirdPartyFinder, adding',matched_path
+                        print('ThirdPartyFinder, adding',matched_path)
                         matches.append(matched_path)
         return matches
 
index f3d42fc..39be524 100644 (file)
@@ -1,5 +1,7 @@
 from unfold.plugin import Plugin
 
+from myslice.settings import logger
+
 class Composite (Plugin):
 
     """a simple base class for plugins that contain/arrange a set of other plugins
@@ -11,17 +13,17 @@ if a valid active_domid is not provided
 
     def __init__ (self, sons=None, active_domid=None, *args, **kwds):
         Plugin.__init__ (self, *args, **kwds)
-        self.sons= sons if sons else []
-        self.active_domid=active_domid
+        self.sons = sons if sons else []
+        self.active_domid = active_domid
         # make sure this is valid, unset otherwise, so we always have exactly one active
         self.check_active_domid()
         
     def check_active_domid(self):
         matches= [ son for son in self.sons if son.domid==self.active_domid ]
         if len(matches)!=1: 
-            print "WARNING: %s has %d valid son(s) for being active - expecting 1, resetting"%\
-                (self,len(matches))
-            self.active_domid=None
+            logger.warning("WARNING: {} has {} valid son(s) for being active - expecting 1, resetting"\
+                           .format(self,len(matches)))
+            self.active_domid = None
         
     def insert (self, plugin):
         self.sons.append(plugin)
@@ -31,9 +33,10 @@ if a valid active_domid is not provided
         # {% for son in sons %} {{ son.rendered }} ...
         def is_active (son,rank):
             # if active_domid is not specified, make the first one active
-            if not self.active_domid: return rank==0
-            return son.domid==self.active_domid
-        ranks=range(len(self.sons))
+            if not self.active_domid:
+                return rank==0
+            return son.domid == self.active_domid
+        ranks = range(len(self.sons))
         env = { 'sons':
                  [ { 'rendered': son.render(request),
                      'rank': rank,
index d4f9e98..7b10be4 100644 (file)
@@ -6,6 +6,8 @@ from django.views.generic.base          import TemplateView
 
 from manifoldapi.manifoldresult            import ManifoldException
 
+from myslice.settings import logger
+
 ###
 # IMPORTANT NOTE
 # the implementation of the classes in this file rely on redefining 'dispatch'
@@ -33,7 +35,6 @@ class LoginRequiredView (TemplateView):
 
 def logout_on_manifold_exception (fun_that_returns_httpresponse):
     def wrapped (request, *args, **kwds):
-#        print 'wrapped by logout_on_manifold_exception'
         try:
             return fun_that_returns_httpresponse(request,*args, **kwds)
         except ManifoldException, manifold_result:
@@ -45,9 +46,9 @@ def logout_on_manifold_exception (fun_that_returns_httpresponse):
             return HttpResponseRedirect ('/')
         except Exception, e:
             # xxx we need to sugarcoat this error message in some error template...
-            print "Unexpected exception",e
+            logger.error("Unexpected exception {}".format(e))
             import traceback
-            traceback.print_exc()
+            logger.error(traceback.format_exc())
             return HttpResponseRedirect ('/')
     return wrapped
 
index 821c662..f8f4eb3 100644 (file)
@@ -9,8 +9,10 @@ from django.template.loader import render_to_string
 from manifoldapi.metadata import MetaData
 
 from unfold.prelude import Prelude
-
+from unfold.sessioncache import SessionCache
+    
 from myslice.configengine import ConfigEngine
+from myslice.settings import logger
 
 # decorator to deflect calls on this Page to its prelude
 def to_prelude (method):
@@ -97,25 +99,17 @@ class Page:
     # needs to be called explicitly and only when metadata is actually required
     # in particular user needs to be logged
     def get_metadata (self):
-        # look in session's cache - we don't want to retrieve this for every request
-        session=self.request.session
-
-        if 'manifold' not in session:
-            session['manifold'] = {}
-        manifold = session['manifold']
-
-        # if cached, use it
-        if 'metadata' in manifold and isinstance(manifold['metadata'],MetaData):
-            if debug: print "Page.get_metadata: return cached value"
-            return manifold['metadata']
+        cached_metadata = SessionCache().get_metadata(self.request)
+        if cached_metadata and isinstance(cached_metadata, MetaData):
+            logger.debug("Page.get_metadata: return cached value")
+            return cached_metadata
 
         metadata_auth = {'AuthMethod':'anonymous'}
 
-        metadata=MetaData (metadata_auth)
+        metadata = MetaData (metadata_auth)
         metadata.fetch(self.request)
-        # store it for next time
-        manifold['metadata']=metadata
-        if debug: print "Page.get_metadata: return new value"
+        SessionCache().store_metadata(self.request, metadata)
+        logger.debug("Page.get_metadata: return new value")
         return metadata
             
     def expose_js_metadata (self):
index 229f196..9a65f59 100644 (file)
@@ -9,30 +9,32 @@ from django.template.loader import render_to_string
 from unfold.page import Page
 from unfold.prelude import Prelude
 
+from myslice.settings import logger
+
 #################### 
 # set DEBUG to
 # . False : silent
 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
 # . True : to debug all plugin
 
-DEBUG= False
-#DEBUG= [ 'SimpleList' ]
-#DEBUG=True
+DEBUG = False
+#DEBUG = [ 'SimpleList' ]
+#DEBUG = True
 
 # decorator to deflect calls on Plugin to its Prelude through self.page.prelude
 def to_prelude (method):
     def actual (self, *args, **kwds):
         if not self.page: # jordan
             return None
-        prelude_method=Prelude.__dict__[method.__name__]
-        return prelude_method(self.page.prelude,*args, **kwds)
+        prelude_method = Prelude.__dict__[method.__name__]
+        return prelude_method(self.page.prelude, *args, **kwds)
     return actual
 
 class Plugin:
 
     # using a simple incremental scheme to generate domids for now
     # we just need this to be unique in a page
-    domid=0
+    domid = 0
 
     # when a domid is not set by the caller, we name plugins after their respective class as well, 
     # so as to limit name clashes between different views
@@ -41,7 +43,7 @@ class Plugin:
     # and maybe xxx we should just enforce that...
     def newdomid(self):
         Plugin.domid += 1
-        return "plugin-%s-%d"%(self.__class__.__name__.lower(),Plugin.domid)
+        return "plugin-{}-{}".format(self.__class__.__name__.lower(), Plugin.domid)
 
     ########## 
     # Constructor
@@ -84,31 +86,34 @@ class Plugin:
                   **settings):
         self.page = page
         # callers can provide their domid for css'ing 
-        if not domid: domid=self.newdomid()
-        self.domid=domid
+        if not domid:
+            domid=self.newdomid()
+        self.domid = domid
         # title is shown when togglable
         #if not title: title="Plugin title for %s"%domid
-        self.title=title
-        self.classname=self._py_classname()
-        self.plugin_classname=self._js_classname()
-        self.visible=visible
-        if togglable is None:           self.togglable=self.default_togglable()
-        else:                           self.togglable=togglable
-        if toggled is None:             self.toggled=self.default_toggled()
-        else:                           self.toggled=toggled
-        if outline_complete is None:    self.outline_complete=self.default_outline_complete()
-        else:                           self.outline_complete=outline_complete
-        if outline_body is None:        self.outline_body=self.default_outline_body()
-        else:                           self.outline_body=outline_body
+        self.title = title
+        self.classname = self._py_classname()
+        self.plugin_classname = self._js_classname()
+        self.visible = visible
+        if togglable is None:           self.togglable = self.default_togglable()
+        else:                           self.togglable = togglable
+        if toggled is None:             self.toggled = self.default_toggled()
+        else:                           self.toggled = toggled
+        if outline_complete is None:    self.outline_complete = self.default_outline_complete()
+        else:                           self.outline_complete = outline_complete
+        if outline_body is None:        self.outline_body = self.default_outline_body()
+        else:                           self.outline_body = outline_body
         # what comes from subclasses
         for (k,v) in settings.iteritems():
-            setattr(self,k,v)
-            if self.need_debug(): print "%s init - subclass setting %s"%(self.classname,k)
+            setattr(self, k, v)
+            if self.need_debug():
+                logger.debug("{} init - subclass setting {}".format(self.classname, k))
         # minimal debugging
         if self.need_debug():
-            print "%s init dbg .... BEG"%self.classname
-            for (k,v) in self.__dict__.items(): print "dbg %s:%s"%(k,v)
-            print "%s init dbg .... END"%self.classname
+            logger.debug("{} init dbg .... BEG".format(self.classname))
+            for (k, v) in self.__dict__.items():
+                logger.debug("dbg {}:{}".format(k, v))
+            logger.debug("{} init dbg .... END".format(self.classname))
         # do this only once the structure is fine
         if self.page: # I assume we can have a None page (Jordan)
             self.page.record_plugin(self)
@@ -132,18 +137,19 @@ class Plugin:
 
     def setting_json (self, setting):
         # TMP: js world expects plugin_uuid
-        if setting=='plugin_uuid':
-            value=self.domid
-        elif setting=='query_uuid':
-            try: value=self.query.query_uuid
-            except: return '%s:"undefined"'%setting
+        if setting == 'plugin_uuid':
+            value = self.domid
+        elif setting == 'query_uuid':
+            try: value = self.query.query_uuid
+            except: return '{}:"undefined"'.format(setting)
         else:
-            value=getattr(self,setting,None)
-            if value is None: value = "unknown-setting-%s"%setting
+            value = getattr(self,setting,None)
+            if value is None:
+                value = "unknown-setting-%s"%setting
         # first try to use to_json method (json.dumps not working on class instances)
-        try:    value_json=value.to_json()
-        except: value_json=json.dumps(value,separators=(',',':'))
-        return "%s:%s"%(setting,value_json)
+        try:    value_json = value.to_json()
+        except: value_json = json.dumps(value,separators=(',',':'))
+        return "{}:{}".format(setting, value_json)
 
     # expose in json format to js the list of fields as described in json_settings_list()
     # and add plugin_uuid: domid in the mix
@@ -151,7 +157,7 @@ class Plugin:
     def settings_json (self):
         exposed_settings=self.json_settings_list()
         if 'query' in exposed_settings:
-            print "WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough"
+            logger.debug("WARNING, cannot expose 'query' directly in json_settings_list, query_uuid is enough")
         result = "{"
         result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
         result += "}"
@@ -170,24 +176,25 @@ class Plugin:
         plugin_content = self.render_content (request)
         # shove this into plugin.html
         env = {}
-        env ['plugin_content']= plugin_content
+        env['plugin_content'] = plugin_content
         env.update(self.__dict__)
         # translate high-level 'toggled' into 4 different booleans
         self.need_toggle = False
-        if self.toggled=='persistent':
+        if self.toggled == 'persistent':
             # start with everything turned off and let the js callback do its job
-            env.update({'persistent_toggle':True,'display_hide_button':False,
-                        'display_show_button':False,'display_body':False})
-        elif self.toggled==False:
-            env.update({'persistent_toggle':False,'display_hide_button':False,
-                        'display_show_button':True,'display_body':False})
+            env.update({'persistent_toggle' : True, 'display_hide_button' : False,
+                        'display_show_button' : False, 'display_body' : False})
+        elif self.toggled == False:
+            env.update({'persistent_toggle' : False, 'display_hide_button' : False,
+                        'display_show_button' : True, 'display_body' : False})
         else:
-            env.update({'persistent_toggle':False,'display_hide_button':True,
-                        'display_show_button':False,'display_body':True})
+            env.update({'persistent_toggle' : False, 'display_hide_button' : True,
+                        'display_show_button' : False, 'display_body' : True})
         if self.need_debug(): 
-            print "rendering plugin.html with env keys %s"%env.keys()
+            logger.debug("rendering plugin.html with env keys {}".format(env.keys()))
             for (k,v) in env.items(): 
-                if "display" in k or "persistent" in k: print k,'->',v
+                if "display" in k or "persistent" in k:
+                    logger.debug("{} -> {}".format(k, v))
         result = render_to_string ('plugin.html',env)
 
         # export this only for relevant plugins
@@ -210,40 +217,38 @@ class Plugin:
         """Should return an HTML fragment"""
         template = self.template_file()
         # start with a fresh one
-        env={}
+        env = {}
         # add our own settings as defaults
         env.update(self.__dict__)
         # then the things explicitly defined in template_env()
         env.update(self.template_env(request))
         if not isinstance (env,dict):
             raise Exception, "%s.template_env returns wrong type"%self.classname
-        result=render_to_string (template, env)
+        result = render_to_string (template, env)
         if self.need_debug():
-            print "%s.render_content: BEG --------------------"%self.classname
-            print "template=%s"%template
-            print "env.keys=%s"%env.keys()
-            #print "env=%s"%env
-            #print result
-            print "%s.render_content: END --------------------"%self.classname
+            logger.debug("{}.render_content: BEG --------------------".format(self.classname))
+            logger.debug("template={}".format(template))
+            logger.debug("env.keys={}".format(env.keys()))
+            logger.debug("{}.render_content: END --------------------".format(self.classname))
         return result
 
     # or from the result of self.requirements()
     def handle_requirements (self, request):
         try:
-            d=self.requirements()
+            d = self.requirements()
             for (k,v) in d.iteritems():
                 if self.need_debug():
-                    print "%s: handling requirement %s"%(self.classname,v)
+                    logger.debug("{}: handling requirement {}".format(self.classname, v))
                 # e.g. js_files -> add_js_files
-                method_name='add_'+k
-                method=Page.__dict__[method_name]
-                method(self.page,v)
+                method_name = 'add_' + k
+                method = Page.__dict__[method_name]
+                method(self.page, v)
         except AttributeError: 
             # most likely the object does not have that method defined, which is fine
             pass
         except:
             import traceback
-            traceback.print_exc()
+            logger.log(traceback.format_exc())
             pass
 
     #################### requirements/prelude management
index 03e6def..13e1d6f 100644 (file)
@@ -2,6 +2,8 @@ from types import StringTypes, ListType
 
 from django.template.loader import render_to_string
 
+from myslice.settings import logger
+
 debug=False
 
 # the need for js_init_chunks is because we need to have the plugins initialized
@@ -53,7 +55,7 @@ class Prelude:
         result += ",".join( [ "%s->%s"%(k,len(getattr(self,k))) for k in Prelude.keys ] )
         return result
     def inspect (self,msg):
-        print self.inspect_string(msg)
+        logger.debug(self.inspect_string(msg))
 
     # first attempt was to use a simple dict like this
     #    env={}
@@ -86,8 +88,9 @@ class Prelude:
         env['all_js_chunks']= self.js_init_chunks + self.js_chunks
         env['css_chunks']=self.css_chunks
         if debug:
-            print "prelude has %d js_files, %d css files, (%d+%d) js chunks and %d css_chunks"%\
-                (len(self.js_files),len(self.css_files),len(self.js_init_chunks),len(self.js_chunks),len(self.css_chunks),)
+            logger.debug("prelude has {} js_files, {} css files, ({}+{}) js chunks and {} css_chunks"\
+                         .format (len(self.js_files), len(self.css_files),
+                                  len(self.js_init_chunks), len(self.js_chunks), len(self.css_chunks),))
         # render this with prelude.html and put the result in header_prelude
         header_prelude = render_to_string ('prelude.html',env)
         return { 'header_prelude' : header_prelude }
diff --git a/unfold/sessioncache.py b/unfold/sessioncache.py
new file mode 100644 (file)
index 0000000..7abb22b
--- /dev/null
@@ -0,0 +1,127 @@
+import uuid
+
+from manifold.util.singleton import Singleton
+
+from myslice.settings import logger
+
+# the key attached to the session object, where we store
+# the uuid attached to that session in this cache
+cache_key = 'cached_uuid'
+
+class _SessionExtension(object):
+    """
+    This object holds all the data we need to attach to a django session object
+    """
+
+    def __init__(self):
+        self.metadata = None
+        self.auth = None
+
+    def __repr__(self):
+        result = "<SessionExtension"
+        if self.metadata: result += " .metadata"
+        if self.auth:     result += " .auth"
+        result += ">"
+        return result
+
+class SessionCache(dict):
+    """
+    As of django1.7, the session object as attached to a django request
+    gets JSON-serialized instead of pickled
+    This breaks our previous or passing data from request to request across
+    a given session - in particular for metadata and auth/session keys
+    Not that the problem is more with metadata as this is a class instance
+    and JSON cannot handle that
+    So instead we decorate the session object with a UID and retrieve all the rest 
+    from the present - singleton - cache instance
+    """
+
+    __metaclass__ = Singleton
+
+    def get_auth(self, request):
+        """
+        Get the auth previously attached to the request's session, or None
+        """
+        result = self._get(request, 'auth')
+        return result
+
+    def store_auth(self, request, auth):
+        """
+        Store the auth object attached to this request's session
+        create that extension if needed
+        """
+        return self._store(request, 'auth', auth)
+
+    def get_metadata(self, request):
+        """
+        retrieve metadata attached to this request's session, or None
+        """
+        return self._get(request, 'metadata')
+
+    def store_metadata(self, request, metadata):
+        """
+        Store the metadata object attached to this request's session
+        create that extension if needed
+        """
+        return self._store(request, 'metadata', metadata)
+
+    def _get(self, request, key):
+        "internal - retrieve key - do not create anything"
+        session = request.session
+        logger.debug("sessioncache._get_{} session={}".format(key, SessionCache._debug_session(session)))
+#        self._debug(request)
+        if cache_key not in session:
+            return None
+        cached_uuid = session[cache_key]
+        if cached_uuid not in self:
+            return None
+        extension = self[cached_uuid]
+        return getattr(extension, key)
+
+    def _store(self, request, key, value):
+        "internal - set key, attach and create extension if needed"
+        session = request.session
+        if cache_key not in session:
+            session[cache_key] = uuid.uuid1().int
+        cached_uuid = session[cache_key]
+        if cached_uuid not in self:
+            self[cached_uuid] = _SessionExtension()
+        extension = self[cached_uuid]
+        setattr(extension, key, value)
+        logger.debug("sessioncache._store_{} session={}".format(key, SessionCache._debug_session(session)))
+#        self._debug(request)
+
+    def end_session(self, request):
+        """
+        Clear all data related to this request's session has we are logging out
+        This is for garbage collection
+        """
+        session = request.session
+        logger.debug("SessionCache.end_session() {}".format(self._debug_session(session)))
+        if cache_key not in session:
+            return
+        cached_uuid = session[cache_key]
+        if cached_uuid in self:
+            del self[cached_uuid]
+
+    def _debug(self, request):
+        session = request.session
+        logger.debug("SessionCache: ---------- with session {}".format(self._debug_session(session)))
+        for k,v in self.iteritems():
+            logger.debug("SessionCache {} -> {}".format(k,v))
+        if cache_key not in session:
+            return
+        cached_uuid = session[cache_key]
+        if cached_uuid not in self:
+            return
+        extension = self[cached_uuid]
+        logger.debug("SessionCache: found extension {}".format(extension))
+        logger.debug("SessionCache: ----------")
+        
+    @staticmethod
+    def _debug_session(session):
+        result = ""
+        result += "{} x {}".format(session, session.keys())
+        if cache_key in session:
+            result += " <{} = {}>".format(cache_key, session[cache_key])
+        return result
index 4ef3cd1..b8b1c91 100644 (file)
@@ -1,3 +1,5 @@
+from __future__ import print_function
+
 """
 This file demonstrates writing tests using the unittest module. These will pass
 when you run "manage.py test".
@@ -14,8 +16,8 @@ class PluginTest(TestCase):
         """
         Tests that 1 + 1 always equals 2.
         """
-        print 'test_basic is broken'
+        print('test_basic is broken')
         return True
         sl = SimpleList (visible=True)
-        print 'rendering', sl.render()
+        print('rendering', sl.render())
         self.assertEqual(1 + 1, 2)