def create_element(self, tag, *children, **attrib): nsattrib = self.makeattribs(**attrib) tag = self.addns(tag) elem = etree.Element(tag, nsattrib) for item in children: if isinstance(item, Promise): item = force_text(item) # assert_pure(item) if isinstance(item, dict): elem.attrib.update(self.makeattribs(**item)) elif isinstance(item, six.string_types): # assert_pure(item) #~ if len(elem) and len(elem[-1]) == 0: if len(elem): last = elem[-1] last.tail = (last.tail or "") + item else: elem.text = (elem.text or "") + item elif etree.iselement(item): elem.append(item) else: raise TypeError("bad argument: %r" % item) #~ print "20130805 added %s --> %s" % (item,self.tostring(elem)) return elem
def iselement(self, *args, **kw): return etree.iselement(*args, **kw)
def format_value(self, v): if etree.iselement(v): return str(etree.tostring(v)) return str(v)
def format_value(self, v): if etree.iselement(v): return html2rst(v, True).strip() return super(RstTable, self).format_value(v).strip()
def py2js(v): """Note that None values are rendered as ``null`` (not ``undefined``. """ # assert _for_user_profile is not None # logger.debug("py2js(%r)",v) for cv in CONVERTERS: v = cv(v) # if isinstance(v,LanguageInfo): # return v.django_code if isinstance(v, Value): return v.as_ext() # v = v.as_ext() # if not isinstance(v, basestring): # raise Exception("20120121b %r is of type %s" % (v,type(v))) # return v if isinstance(v, Promise): # v = force_text(v) return json.dumps(force_text(v.encode('utf8'))) if isinstance(v, types.GeneratorType): return "".join([py2js(x) for x in v]) if etree.iselement(v): return json.dumps(force_text(etree.tostring(v))) # try: # return json.dumps(force_text(etree.tostring(v))) # except Exception as e: # return json.dumps("Failed to render {!r} : {}".format(v, e)) # if type(v) is types.GeneratorType: # raise Exception("Please don't call the generator function yourself") # return "\n".join([ln for ln in v]) if callable(v): # print 20120114, repr(v) # raise Exception("Please call the function yourself") return "\n".join([ln for ln in v()]) if isinstance(v, js_code): return str(v.s) # v.s might be a unicode if v is None: # return 'undefined' return 'null' if isinstance(v, (list, tuple)): # (types.ListType, types.TupleType): elems = [py2js(x) for x in v if (not isinstance(x, VisibleComponent)) or x.get_view_permission(get_user_profile())] return "[ %s ]" % ", ".join(elems) if isinstance(v, dict): items = [ # i for i in sorted(v.items(), key=lambda x: str(x)) # i for i in sorted(v.items()) i for i in v.items() if (not isinstance(v, VisibleComponent)) or v.get_view_permission(get_user_profile())] if six.PY2: # "sorted(v.items())" without sortkey caused TypeError when # the dictionary contained a mixture of unicode and # future.types.newstr objects. def sortkey(x): if isinstance(x[0], newstr): return six.text_type(x[0]) return x[0] else: def sortkey(x): return x[0] items = sorted(items, key=sortkey) # try: # items = sorted(items, key=sortkey) # except TypeError as e: # raise TypeError("Failed to sort {0!r} : {1}".format(items, e)) return "{ %s }" % ", ".join( ["%s: %s" % (py2js(k), py2js(i)) for k, i in items]) if isinstance(v, bool): # types.BooleanType: return str(v).lower() if isinstance(v, Quantity): return '"%s"' % v if isinstance(v, (int, decimal.Decimal, fractions.Fraction)): return str(v) if isinstance(v, IncompleteDate): return '"%s"' % v.strftime(settings.SITE.date_format_strftime) if isinstance(v, datetime.datetime): return '"%s"' % v.strftime(settings.SITE.datetime_format_strftime) if isinstance(v, datetime.time): return '"%s"' % v.strftime(settings.SITE.time_format_strftime) if isinstance(v, datetime.date): if v.year < 1900: v = IncompleteDate.from_date(v) return '"%s"' % v.strftime(settings.SITE.date_format_strftime) return '"%s"' % v.strftime(settings.SITE.date_format_strftime) if isinstance(v, float): return repr(v) # return json.encoder.encode_basestring(v) # print repr(v) # http://docs.djangoproject.com/en/dev/topics/serialization/ # if not isinstance(v, (str,unicode)): # raise Exception("20120121 %r is of type %s" % (v,type(v))) return json.dumps(v)
def py2js(v, compact=True): """Note that None values are rendered as ``null`` (not ``undefined``. """ # assert _for_user_profile is not None # logger.debug("py2js(%r)",v) for cv in CONVERTERS: v = cv(v) # if isinstance(v,LanguageInfo): # return v.django_code if isinstance(v, Value): return v.as_ext() # v = v.as_ext() # if not isinstance(v, basestring): # raise Exception("20120121b %r is of type %s" % (v,type(v))) # return v if isinstance(v, Promise): # v = force_text(v) return json.dumps(force_text(v.encode('utf8'))) if isinstance(v, types.GeneratorType): return "".join([py2js(x, compact=compact) for x in v]) if etree.iselement(v): return json.dumps(force_text(etree.tostring(v))) # try: # return json.dumps(force_text(etree.tostring(v))) # except Exception as e: # return json.dumps("Failed to render {!r} : {}".format(v, e)) # if type(v) is types.GeneratorType: # raise Exception("Please don't call the generator function yourself") # return "\n".join([ln for ln in v]) if callable(v): # print 20120114, repr(v) # raise Exception("Please call the function yourself") return "\n".join([ln for ln in v()]) if isinstance(v, js_code): return str(v.s) # v.s might be a unicode if v is None: # return 'undefined' return 'null' if isinstance(v, (list, tuple)): # (types.ListType, types.TupleType): elems = [py2js(x, compact=compact) for x in v if (not isinstance(x, VisibleComponent)) or x.get_view_permission(get_user_profile())] sep = ", " if compact else ", \n" return "[ %s ]" % sep.join(elems) if isinstance(v, dict): items = [ # i for i in sorted(v.items(), key=lambda x: str(x)) # i for i in sorted(v.items()) i for i in v.items() if (not isinstance(v, VisibleComponent)) or v.get_view_permission(get_user_profile())] if six.PY2: # "sorted(v.items())" without sortkey caused TypeError when # the dictionary contained a mixture of unicode and # future.types.newstr objects. def sortkey(x): if isinstance(x[0], newstr): return six.text_type(x[0]) return x[0] else: def sortkey(x): return x[0] items = sorted(items, key=sortkey) # try: # items = sorted(items, key=sortkey) # except TypeError as e: # raise TypeError("Failed to sort {0!r} : {1}".format(items, e)) sep = ", " if compact else ", \n" return "{ %s }" % sep.join( ["%s: %s" % (py2js(k, compact=compact), py2js(i, compact=compact)) for k, i in items]) if isinstance(v, bool): # types.BooleanType: return str(v).lower() if isinstance(v, Quantity): return '"%s"' % v if isinstance(v, (int, decimal.Decimal, fractions.Fraction)): return str(v) if isinstance(v, IncompleteDate): return '"%s"' % v.strftime(settings.SITE.date_format_strftime) if isinstance(v, datetime.datetime): return '"%s"' % v.strftime(settings.SITE.datetime_format_strftime) if isinstance(v, datetime.time): return '"%s"' % v.strftime(settings.SITE.time_format_strftime) if isinstance(v, datetime.date): if v.year < 1900: v = IncompleteDate.from_date(v) return '"%s"' % v.strftime(settings.SITE.date_format_strftime) return '"%s"' % v.strftime(settings.SITE.date_format_strftime) if isinstance(v, float): return repr(v) # return json.encoder.encode_basestring(v) # print repr(v) # http://docs.djangoproject.com/en/dev/topics/serialization/ # if not isinstance(v, (str,unicode)): # raise Exception("20120121 %r is of type %s" % (v,type(v))) return json.dumps(v, sort_keys=True, indent=4, separators=(',', ': ') )