various changes around settings management
authorThierry Parmentelat <thierry.parmentelat@inria.fr>
Thu, 28 Feb 2013 15:41:50 +0000 (16:41 +0100)
committerThierry Parmentelat <thierry.parmentelat@inria.fr>
Thu, 28 Feb 2013 15:41:50 +0000 (16:41 +0100)
turns out I had totally misunderstaood what the scope of the json initialization should be
so instead of trying to expose everything to json we require each
plugin class to define json_settings_list() so as to decide what
really gets exposed
---
this version is currently very rough/broken but I feel like I need to
commit this before it causes too much harm

auth/views.py
engine/composite.py
engine/plugin.py
engine/views.py
myslice/urls.py
myslice/viewutils.py
plugins/quickfilter.py
plugins/simplelist.py
plugins/slicelist.py

index 45fe637..5237a64 100644 (file)
@@ -29,7 +29,7 @@ def login_user(request):
             if user.is_active:
                 login(request, user)
                 #state = "You're successfully logged in!"
-                return HttpResponseRedirect ('/')
+                return HttpResponseRedirect ('/login-ok')
             else:
                 env['state'] = "Your account is not active, please contact the site admin."
                 return render_to_response('view-login.html',env, context_instance=RequestContext(request))
index 6d6ceec..49ea0b5 100644 (file)
@@ -22,7 +22,6 @@ class Composite (Plugin):
                  [ { 'rendered': son.render(request),
                      'rank': rank,
                      'active': is_active(son),
-                     # this should probably come from son._settings..
                      'title': son.title,
                      'domid': son.domid,
                      'classname': son.classname,
index fc68c48..f3fae50 100644 (file)
@@ -14,8 +14,8 @@ from engine.prelude import Prelude
 # . [ 'SliceList', 'TabbedView' ] : to debug these classes
 # . True : to debug all plugin
 
-#DEBUG= [ 'Tabs' ]
 DEBUG= False
+DEBUG= [ 'SimpleList' ]
 
 class Plugin:
 
@@ -48,48 +48,58 @@ class Plugin:
     # 
     def __init__ (self, title, domid=None,
                   visible=True, togglable=True, toggled=True, **settings):
-        # what is in this dictionary will get exposed to template and to javascript
-        self._settings=settings
         self.title=title
         if not domid: domid=Plugin.newdomid()
         self.domid=domid
         self.classname=self._classname()
-        self.add_to_settings ( ['title', 'domid', 'classname'] )
         self.visible=visible
         self.togglable=togglable
         self.toggled=toggled
-        self.add_to_settings( ['visible','togglable','toggled'] )
-        # we store as a dictionary the arguments passed to constructor
-        # e.g. SimpleList (list=[1,2,3]) => _settings = { 'list':[1,2,3] }
-        # our own settings are not made part of _settings but could be..
+        # 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)
+        # minimal debugging
         if self.need_debug():
-            print "Plugin.__init__ Created plugin with settings %s"%self._settings.keys()
-
-    # subclasses might handle some fields in their own way, 
-    # in which case this call is needed to capture that setting
-    # see e.g. SimpleList or SliceList for an example of that
-    def add_to_settings (self, setting_name_s):
-        if not isinstance (setting_name_s, list):
-            self._settings[setting_name_s]=getattr(self,setting_name_s)
-        else:
-            for setting_name in setting_name_s:
-                self._settings[setting_name]=getattr(self,setting_name)
+            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
 
     def _classname (self): 
         try:    return self.__class__.__name__
         except: return 'Plugin'
 
-    # shorthands to inspect _settings
-    def get_setting (self, setting, default=None):
-        if setting not in self._settings: return default
-        else:                             return self._settings[setting]
-
     ##########
     def need_debug (self):
         if not DEBUG:           return False
         if DEBUG is True:       return True
         else:                   return self.classname in DEBUG
 
+    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.uuid
+            except: return '%s:"undefined"'%setting
+        else:
+            value=getattr(self,setting,None)
+            if not value: 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)
+
+    # expose in json format to js the list of fields as described in json_settings_list()
+    # and add plugin_uuid: domid in the mix
+    # NOTE this plugin_uuid thing might occur in js files from joomla/js, ** do not rename **
+    def settings_json (self):
+        result = "{"
+        result += "plugin_uuid:%s,"%self.domid
+        result += ",".join([ self.setting_json(setting) for setting in self.json_settings_list() ])
+        result += "}"
+        return result
+
     # returns the html code for that plugin
     # in essence, wraps the results of self.render_content ()
     def render (self, request):
@@ -100,17 +110,10 @@ class Plugin:
         # shove this into plugin.html
         env = {}
         env ['plugin_content']= plugin_content
-        env.update(self._settings)
+        env.update(self.__dict__)
         result = render_to_string ('plugin.html',env)
 
-        # expose _settings in json format to js, and add plugin_uuid: domid in the mix
-        # NOTE this plugin_uuid thing might occur in js files, ** do not rename **
-        js_env = { 'plugin_uuid' : self.domid }
-        js_env.update (self._settings)
-        for k in self.exclude_from_json():
-            if k in js_env: del js_env[k]
-        settings_json = json.dumps (js_env, separators=(',',':'))
-        env ['settings_json' ] = settings_json
+        env ['settings_json' ] = self.settings_json()
         # compute plugin-specific initialization
         js_init = render_to_string ( 'plugin-setenv.js', env )
         self.add_js_chunks (request, js_init)
@@ -129,9 +132,6 @@ class Plugin:
         env=self.template_env(request)
         if not isinstance (env,dict):
             raise Exception, "%s.template_env returns wrong type"%self.classname
-        # expose this class's settings to the template
-        # xxx we might need to check that this does not overwrite env..
-        env.update(self._settings)
         result=render_to_string (template, env)
         if self.need_debug():
             print "%s.render_content: BEG --------------------"%self.classname
@@ -213,6 +213,13 @@ class Plugin:
 #                 'css_chunk': [],       # likewise for css scripts
 #                 }
     
-    # for better performance
-    # you can specify a list of keys that won't be exposed as json attributes
-    def exclude_from_json (self): return []
+#    # for better performance
+#    # you can specify a list of keys that won't be exposed as json attributes
+#    def exclude_from_json (self): return []
+
+    # mandatory : define the fields that need to be exposed to json as part of 
+    # plugin initialization
+    # mention 'domid' if you need plugin_uuid
+    # also 'query_uuid' gets replaced with query.uuid
+    def json_settings_list (self): return ['json_settings_list-must-be-redefined']
+
index 4a26b66..caf699f 100644 (file)
@@ -25,28 +25,28 @@ def test_plugin_view (request):
     
     main_plugin = \
         VerticalLayout ( title='title for the vertical layout',
-        sons = [ SimpleList (title='SimpleList and dataTables',
-                             list=hard_wired_list, 
-                             header='Hard wired', 
-                             foo='the value for foo',
-                             with_datatables=True,
-                             toggled=False),
-                 Tabs (title='Sample Tabs',
-                       # *** we select this one to be the active tab ***
-                       active='raw2',
-                       sons = [ Raw (title='a raw plugin',domid='raw1',
-                                     togglable=False,
-                                     html= 3*lorem_p),
-                                SliceList(title='a slice list',
-                                          togglable=False,
-                                          list=hard_wired_slice_names),
-                                Raw (title='raw title',domid='raw2',
-                                     togglable=False,html=lorem) ]),
-                 SimpleList (title='SimpleList with slice names', 
-                             list=hard_wired_slice_names,
-                             ),
-                 QuickFilter (list=quickfilter_criterias,
-                              title='QuickFilter in main content') ] )
+                         sons = [ SimpleList (title='SimpleList and dataTables',
+                                              list=hard_wired_list, 
+                                              header='Hard wired', 
+                                              foo='the value for foo',
+                                              with_datatables=True,
+                                              toggled=False),
+                                  Tabs (title='Sample Tabs',
+                                        # *** we select this one to be the active tab ***
+                                        active='raw2',
+                                        sons = [ Raw (title='a raw plugin',domid='raw1',
+                                                      togglable=False,
+                                                      html= 3*lorem_p),
+                                                 SliceList(title='a slice list',
+                                                           togglable=False,
+                                                           list=hard_wired_slice_names),
+                                                 Raw (title='raw title',domid='raw2',
+                                                      togglable=False,html=lorem) ]),
+                                  SimpleList (title='SimpleList with slice names', 
+                                              list=hard_wired_slice_names,
+                                              ),
+                                  QuickFilter (list=quickfilter_criterias,
+                                               title='QuickFilter in main content') ] )
     # define 'content_main' to the template engine
     template_env [ 'content_main' ] = main_plugin.render(request)
 
index c76ad8b..3b6844e 100644 (file)
@@ -8,6 +8,11 @@ from django.conf.urls import patterns, include, url
 from django.template.loader import add_to_builtins
 add_to_builtins('insert_above.templatetags.insert_tags')
 
+# main entry point (set to the / URL)
+default_view='engine.views.test_plugin_view'
+# where to be redirected after login
+after_login_view='myslice.dashboard.dashboard_view'
+
 urlpatterns = patterns(
     '',
     # Examples:
@@ -19,7 +24,8 @@ urlpatterns = patterns(
 
     # Uncomment the next line to enable the admin:
     # url(r'^admin/', include(admin.site.urls)),
-    (r'^/?$', 'engine.views.test_plugin_view'),
+    (r'^/?$', default_view),
+    (r'^/login-ok?$', after_login_view),
     # seems to be what login_required uses to redirect ...
     (r'^accounts/login/$', 'auth.views.login_user'),
     (r'^login/?$', 'auth.views.login_user'),
@@ -30,4 +36,5 @@ urlpatterns = patterns(
     (r'^tab/?$', 'slice.views.tab_view'),
     (r'^scroll/?$', 'slice.views.scroll_view'),
     (r'^plugin/?$', 'engine.views.test_plugin_view'),
+    (r'^dashboard/?$', 'myslice.dashboard.dashboard_view'),
 )
index ecdd81f..cd104e0 100644 (file)
@@ -6,6 +6,7 @@ standard_topmenu_items = [ { 'label':'Plugin', 'href': '/plugin/'},
                            { 'label':'Slice',  'href': '/slice/'},
                            { 'label':'Scroll', 'href': '/scroll/'},
                            { 'label':'Tab', 'href': '/tab/'},
+                           { 'label':'Dashboard', 'href': '/dashboard/'},
                            ]
 
 #login_out_items = { False: { 'label':'Login', 'href':'/login/'},
index d6dc484..77929d7 100644 (file)
@@ -5,9 +5,7 @@ class QuickFilter (Plugin) :
     def __init__ (self, list=[], with_datatables=False, **settings):
         Plugin.__init__ (self, **settings)
         self.list=list
-        self.add_to_settings ('list')
         self.with_datatables = with_datatables
-        self.add_to_settings ('with_datatables')
         
 
     def title (self) : return "Title for Quick "
@@ -22,4 +20,4 @@ class QuickFilter (Plugin) :
 
     def exclude_from_json (self):
         return ['list']
-  
\ No newline at end of file
+  
index 5821bfb..28c73f4 100644 (file)
@@ -8,10 +8,7 @@ class SimpleList (Plugin) :
     def __init__ (self, list=[], with_datatables=False, **settings):
         Plugin.__init__ (self, **settings)
         self.list=list
-# don't expose this as it's big and 
-        self.add_to_settings ('list')
         self.with_datatables = with_datatables
-        self.add_to_settings ('with_datatables')
 
     # SimpleList is useless per se anyways
     def template_file (self): return "simplelist.html"
@@ -27,6 +24,6 @@ class SimpleList (Plugin) :
 # for tests
 #                 'js_chunks' : "/* a javascript chunk */",       
 #                 'css_chunks': "/* a css style */ ",
+    
+    def json_settings_list (self): return ['plugin_uuid', 'query','query_uuid','key','value']
 
-    def exclude_from_json (self):
-        return ['list']
index 1f622aa..c980423 100644 (file)
@@ -5,7 +5,6 @@ class SliceList (SimpleList):
     def __init__ (self, list=[], **settings):
         SimpleList.__init__(self, **settings)
         self.list = [ "<a href='/slice/%s/' class='slicelist'>%s</a>"%(x,x) for x in list ]
-        self.add_to_settings ('list')
 
 #    def requirements (self):
 #        reqs=SimpleList.requirements(self)