don't depends on simplejson outside web/ tls-sprint
authorsylvain.thenault@logilab.fr
Mon, 04 May 2009 11:47:33 +0200
branchtls-sprint
changeset 1635 866563e2d0fc
parent 1634 dbb70cdca535
child 1636 66f62f8ef8d8
don't depends on simplejson outside web/
appobject.py
common/uilib.py
web/__init__.py
web/views/basecontrollers.py
web/views/calendar.py
web/views/startup.py
web/views/tableview.py
--- a/appobject.py	Mon May 04 10:52:00 2009 +0200
+++ b/appobject.py	Mon May 04 11:47:33 2009 +0200
@@ -8,8 +8,6 @@
 
 from datetime import datetime, timedelta
 
-from simplejson import dumps
-
 from logilab.common.decorators import classproperty
 from logilab.common.deprecation import obsolete
 
@@ -244,6 +242,7 @@
         """register the given user callback and return an url to call it ready to be
         inserted in html
         """
+        from simplejson import dumps
         self.req.add_js('cubicweb.ajax.js')
         cbname = self.req.register_onetime_callback(cb, *args)
         msg = dumps(msg or '')
--- a/common/uilib.py	Mon May 04 10:52:00 2009 +0200
+++ b/common/uilib.py	Mon May 04 11:47:33 2009 +0200
@@ -14,7 +14,7 @@
 import re
 from datetime import datetime, date, timedelta
 from urllib import quote as urlquote
-from cStringIO import StringIO
+from StringIO import StringIO
 
 from logilab.mtconverter import html_escape, html_unescape
 
@@ -239,31 +239,6 @@
     """builds a HTML link that uses the js toggleVisibility function"""
     return u'<a href="%s">%s</a>' % (toggle_action(nodeid), label)
 
-def ajax_replace_url(nodeid, rql, vid=None, swap=False, **extraparams):
-    """builds a replacePageChunk-like url
-    >>> ajax_replace_url('foo', 'Person P')
-    "javascript: replacePageChunk('foo', 'Person%20P');"
-    >>> ajax_replace_url('foo', 'Person P', 'oneline')
-    "javascript: replacePageChunk('foo', 'Person%20P', 'oneline');"
-    >>> ajax_replace_url('foo', 'Person P', 'oneline', name='bar', age=12)
-    "javascript: replacePageChunk('foo', 'Person%20P', 'oneline', {'age':12, 'name':'bar'});"
-    >>> ajax_replace_url('foo', 'Person P', name='bar', age=12)
-    "javascript: replacePageChunk('foo', 'Person%20P', 'null', {'age':12, 'name':'bar'});"
-    """
-    params = [repr(nodeid), repr(urlquote(rql))]
-    if extraparams and not vid:
-        params.append("'null'")
-    elif vid:
-        params.append(repr(vid))
-    if extraparams:
-        import simplejson
-        params.append(simplejson.dumps(extraparams))
-    if swap:
-        params.append('true')
-    return "javascript: replacePageChunk(%s);" % ', '.join(params)
-
-
-from StringIO import StringIO
 
 def ureport_as_html(layout):
     from logilab.common.ureports import HTMLWriter
@@ -507,23 +482,6 @@
         return newfunc
 
 
-def jsonize(function):
-    import simplejson
-    def newfunc(*args, **kwargs):
-        ret = function(*args, **kwargs)
-        if isinstance(ret, decimal.Decimal):
-            ret = float(ret)
-        elif isinstance(ret, (date, datetime)):
-            ret = ret.strftime('%Y-%m-%d %H:%M')
-        elif isinstance(ret, timedelta):
-            ret = (ret.days * 24*60*60) + ret.seconds
-        try:
-            return simplejson.dumps(ret)
-        except TypeError:
-            return simplejson.dumps(repr(ret))
-    return newfunc
-
-
 def htmlescape(function):
     def newfunc(*args, **kwargs):
         ret = function(*args, **kwargs)
--- a/web/__init__.py	Mon May 04 10:52:00 2009 +0200
+++ b/web/__init__.py	Mon May 04 11:47:33 2009 +0200
@@ -7,10 +7,12 @@
 :contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr
 """
 __docformat__ = "restructuredtext en"
+_ = unicode
 
-from cubicweb.web._exceptions import *    
+from simplejson import dumps
 
-_ = unicode
+from cubicweb.web._exceptions import *
+
 
 INTERNAL_FIELD_VALUE = '__cubicweb_internal_field__'
 
@@ -37,3 +39,44 @@
 
 # XXX deprecated
 FACETTES = set()
+
+
+
+def json_dumps(value):
+    if isinstance(value, decimal.Decimal):
+        value = float(value)
+    elif isinstance(value, (date, datetime)):
+        value = value.strftime('%Y-%m-%d %H:%M')
+    elif isinstance(value, timedelta):
+        value = (value.days * 24*60*60) + value.seconds
+    try:
+        return simplejson.dumps(value)
+    except TypeError:
+        return simplejson.dumps(repr(value))
+
+def jsonize(function):
+    def newfunc(*args, **kwargs):
+        return json_dumps(function(*args, **kwargs))
+    return newfunc
+
+def ajax_replace_url(nodeid, rql, vid=None, swap=False, **extraparams):
+    """builds a replacePageChunk-like url
+    >>> ajax_replace_url('foo', 'Person P')
+    "javascript: replacePageChunk('foo', 'Person%20P');"
+    >>> ajax_replace_url('foo', 'Person P', 'oneline')
+    "javascript: replacePageChunk('foo', 'Person%20P', 'oneline');"
+    >>> ajax_replace_url('foo', 'Person P', 'oneline', name='bar', age=12)
+    "javascript: replacePageChunk('foo', 'Person%20P', 'oneline', {'age':12, 'name':'bar'});"
+    >>> ajax_replace_url('foo', 'Person P', name='bar', age=12)
+    "javascript: replacePageChunk('foo', 'Person%20P', 'null', {'age':12, 'name':'bar'});"
+    """
+    params = [repr(nodeid), repr(urlquote(rql))]
+    if extraparams and not vid:
+        params.append("'null'")
+    elif vid:
+        params.append(repr(vid))
+    if extraparams:
+        params.append(json_dumps(extraparams))
+    if swap:
+        params.append('true')
+    return "javascript: replacePageChunk(%s);" % ', '.join(params)
--- a/web/views/basecontrollers.py	Mon May 04 10:52:00 2009 +0200
+++ b/web/views/basecontrollers.py	Mon May 04 11:47:33 2009 +0200
@@ -20,7 +20,7 @@
 from cubicweb.selectors import yes, match_user_groups
 from cubicweb.view import STRICT_DOCTYPE
 from cubicweb.common.mail import format_mail
-from cubicweb.web import ExplicitLogin, Redirect, RemoteCallFailed
+from cubicweb.web import ExplicitLogin, Redirect, RemoteCallFailed, json_dumps
 from cubicweb.web.formrenderers import FormRenderer
 from cubicweb.web.controller import Controller
 from cubicweb.web.views import vid_from_rset
@@ -42,8 +42,7 @@
     """
     def wrapper(self, *args, **kwargs):
         self.req.set_content_type('application/json')
-        result = func(self, *args, **kwargs)
-        return simplejson.dumps(result)
+        return json_dumps(func(self, *args, **kwargs))
     wrapper.__name__ = func.__name__
     return wrapper
 
--- a/web/views/calendar.py	Mon May 04 10:52:00 2009 +0200
+++ b/web/views/calendar.py	Mon May 04 11:47:33 2009 +0200
@@ -15,7 +15,7 @@
 from cubicweb.selectors import implements
 from cubicweb.utils import strptime, date_range, todate
 from cubicweb.view import EntityView
-from cubicweb.common.uilib import ajax_replace_url
+from cubicweb.web import ajax_replace_url
 
 _ = unicode
 
--- a/web/views/startup.py	Mon May 04 10:52:00 2009 +0200
+++ b/web/views/startup.py	Mon May 04 11:47:33 2009 +0200
@@ -13,8 +13,8 @@
 
 from cubicweb.view import StartupView
 from cubicweb.selectors import match_user_groups
-from cubicweb.common.uilib import ureport_as_html, ajax_replace_url
-from cubicweb.web import uicfg, httpcache
+from cubicweb.common.uilib import ureport_as_html
+from cubicweb.web import ajax_replace_url, uicfg, httpcache
 from cubicweb.web.views.management import SecurityViewMixIn
 
 
--- a/web/views/tableview.py	Mon May 04 10:52:00 2009 +0200
+++ b/web/views/tableview.py	Mon May 04 11:47:33 2009 +0200
@@ -14,7 +14,8 @@
 from cubicweb.selectors import nonempty_rset, match_form_params
 from cubicweb.utils import make_uid
 from cubicweb.view import EntityView, AnyRsetView
-from cubicweb.common.uilib import toggle_action, limitsize, jsonize, htmlescape
+from cubicweb.common.uilib import toggle_action, limitsize, htmlescape
+from cubicweb.web import jsonize
 from cubicweb.web.htmlwidgets import (TableWidget, TableColumn, MenuWidget,
                                       PopupBoxMenu, BoxLink)
 from cubicweb.web.facet import prepare_facets_rqlst, filter_hiddens
@@ -44,7 +45,7 @@
                                         'displayfilter': displayfilter})
             return self.show_hide_actions(divid, not hidden)
         return ()
-    
+
     def _generate_form(self, divid, baserql, fwidgets, hidden=True, vidargs={}):
         """display a form to filter table's content. This should only
         occurs when a context eid is given
@@ -88,7 +89,7 @@
             else:
                 displaycols = range(len(self.rset.syntax_tree().children[0].selection))
         return displaycols
-    
+
     def call(self, title=None, subvid=None, displayfilter=None, headers=None,
              displaycols=None, displayactions=None, actions=(), divid=None,
              cellvids=None, cellattrs=None):
@@ -169,7 +170,7 @@
         if currentlydisplayed:
             return [(showhide, showlabel, 'hidden', '%sShow' % divid),
                     (showhide, hidelabel, None, '%sHide' % divid)]
-        return [(showhide, showlabel, None, '%sShow' % divid), 
+        return [(showhide, showlabel, None, '%sShow' % divid),
                 (showhide, hidelabel, 'hidden', '%sHide' % divid)]
 
     def render_actions(self, divid, actions):
@@ -184,7 +185,7 @@
             menu.append(BoxLink(url, label, klass, ident=ident, escape=True))
         box.render(w=self.w)
         self.w(u'<div class="clear"/>')
-        
+
     def get_columns(self, rqlstdescr, displaycols, headers, subvid, cellvids,
                     cellattrs, mainindex):
         columns = []
@@ -218,11 +219,11 @@
             # add column
             columns.append(column)
         return columns
-        
+
 
     def render(self, cellvid, row, col, w):
         self.view('cell', self.rset, row=row, col=col, cellvid=cellvid, w=w)
-        
+
     def get_rows(self):
         return self.rset
 
@@ -251,12 +252,12 @@
     finalview = 'editable-final'
     title = _('editable-table')
 
-    
+
 class CellView(EntityView):
     __select__ = nonempty_rset()
-    
+
     id = 'cell'
-    
+
     def cell_call(self, row, col, cellvid=None):
         """
         :param row, col: indexes locating the cell value in view's result set
@@ -277,13 +278,13 @@
 
 class InitialTableView(TableView):
     """same display as  table view but consider two rql queries :
-    
+
     * the default query (ie `rql` form parameter), which is only used to select
       this view and to build the filter form. This query should have the same
       structure as the actual without actual restriction (but link to
       restriction variables) and usually with a limit for efficiency (limit set
       to 2 is advised)
-      
+
     * the actual query (`actualrql` form parameter) whose results will be
       displayed with default restrictions set
     """
@@ -292,7 +293,7 @@
     # should not be displayed in possible view since it expects some specific
     # parameters
     title = None
-    
+
     def call(self, title=None, subvid=None, headers=None, divid=None,
              displaycols=None, displayactions=None):
         """Dumps a table displaying a composite query"""