utils.py
changeset 3293 69c0ba095536
parent 3155 14e30e2520d7
parent 3231 3ee43e2f8560
child 3369 7b88d12b4ee2
--- a/utils.py	Tue Sep 15 15:01:41 2009 +0200
+++ b/utils.py	Thu Sep 17 15:16:53 2009 +0200
@@ -12,10 +12,12 @@
 import locale
 from md5 import md5
 import sys
+import datetime as pydatetime
 from datetime import datetime, timedelta, date
 from time import time, mktime
 from random import randint, seed
 from calendar import monthrange
+import decimal
 
 # initialize random seed from current time
 seed()
@@ -263,7 +265,6 @@
         w = self.write
         # 1/ variable declaration if any
         if self.jsvars:
-            from simplejson import dumps
             w(u'<script type="text/javascript"><!--//--><![CDATA[//><!--\n')
             for var, value in self.jsvars:
                 w(u'%s = %s;\n' % (var, dumps(value)))
@@ -355,3 +356,27 @@
         return False
     __answer[0] = True
     return True
+
+try:
+    # may not be there is cubicweb-web not there
+    from simplejson import JSONEncoder, dumps
+except ImportError:
+    pass
+else:
+    class CubicWebJsonEncoder(JSONEncoder):
+        """define a simplejson encoder to be able to encode yams std types"""
+        def default(self, obj):
+            if isinstance(obj, datetime):
+                return obj.strftime('%Y/%m/%d %H:%M:%S')
+            elif isinstance(obj, date):
+                return obj.strftime('%Y/%m/%d')
+            elif isinstance(obj, pydatetime.time):
+                return obj.strftime('%H:%M:%S')
+            elif isinstance(obj, decimal.Decimal):
+                return float(obj)
+            try:
+                return simplejson.JSONEncoder.default(self, obj)
+            except TypeError:
+                # we never ever want to fail because of an unknown type,
+                # just return None in those cases.
+                return None