Beispiel #1
0
	def _getRowFormatter(self):
		"""returns a callable returning a rendered row in HTML (as used for the
		stan xml tag).
		"""
		source = [
			"def formatRow(row, rowAttrs=''):",
			"  res = ['<tr%s>'%rowAttrs]",]
		for index, (name, _, wantsRow) in enumerate(self.formatterSeq):
			if wantsRow:
				source.append("  val = formatters[%d](row)"%index)
			else:
				source.append("  val = formatters[%d](row[%s])"%(index, repr(name)))
			source.extend([
#				"  import code;code.interact(local=locals())",
				"  if val is None:",
				"    val = 'N/A'",
				"  if isinstance(val, basestring):",
				"    serFct = escapeForHTML",
				"  else:",
				"    serFct = flatten",
				"  res.append('<td>%s</td>'%serFct(val))",])
		source.extend([
			"  res.append('</tr>')",
			"  return ''.join(res)"])

		return utils.compileFunction("\n".join(source), "formatRow", {
				"formatters": [p[1] for p in self.formatterSeq],
				"escapeForHTML": common.escapeForHTML,
				"flatten": flat.flatten})
 def makeGetPrimaryFunction(instance):
     funcSrc = ('def getPrimaryIn(row):\n'
                '	return (%s)') % (" ".join([
                    'row["%s"],' % name
                    for name in getattr(instance, self.name_)
                ]))
     return utils.compileFunction(funcSrc, "getPrimaryIn")
Beispiel #3
0
def _getTupleAdder(table):
    """returns a function that adds a tuple as returned by the database
	to table.

	This thing is only necessary because of the insanity of having to
	mash metadata into table rows when STC-S strings need to be generated
	for TAP.  Sigh.
	"""
    stcsOutputCols = []
    for colInd, col in enumerate(table.tableDef):
        # needMunging set above.  Sigh.
        if getattr(col, "needMunging", False):
            stcsOutputCols.append((colInd, col))
    if not stcsOutputCols:  # Yay!
        return table.addTuple
    else:  # Sigh.  I need to define a function fumbling the mess together.
        parts, lastInd = [], 0
        for index, col in stcsOutputCols:
            if lastInd != index:
                parts.append("row[%s:%s]" % (lastInd, index))
            parts.append("(row[%s].asSTCS(%r),)" %
                         (index, stc.getTAPSTC(col.stc)))
            lastInd = index + 1
        if lastInd != index:
            parts.append("row[%s:%s]" % (lastInd, len(table.tableDef.columns)))
        return utils.compileFunction(
            "def addTuple(row): table.addTuple(%s)" % ("+".join(parts)),
            "addTuple", locals())
Beispiel #4
0
    def _compileMapFunction(self, funcLines):
        """helps _make(Dict|Tuple)Factory.
		"""
        return utils.compileFunction(
            "\n".join(funcLines),
            "buildRec",
            useGlobals=dict(("map%d" % index, mapper)
                            for index, mapper in enumerate(self.mappers)))
Beispiel #5
0
 def feed(self, ctx, instance, literal):
     if ctx.restricted:
         raise common.RestrictedElement("codeItems")
     attrdef.UnicodeAttribute.feed(self, ctx, instance, literal)
     src = utils.fixIndentation(getattr(instance, self.name_),
                                "  ",
                                governingLine=1)
     src = "def makeRows():\n" + src + "\n"
     instance.iterRowsFromCode = utils.compileFunction(
         src, "makeRows", useGlobals={"context": ctx})
Beispiel #6
0
def _getRowMaker(table):
	"""returns a function turning a VOTable tuple to a database row
	for table.

	This is mainly just building a row dictionary, except we also
	parse xtyped columns.
	"""
	from gavo.base.literals import parseDefaultDatetime #noflake: code gen
	from gavo.stc import parseSimpleSTCS, simpleSTCSToPolygon #noflake: code gen

	parts = []
	for colInd, col in enumerate(table.tableDef):
		valCode = "row[%d]"%colInd
		parts.append("%s: %s"%(repr(col.key), valCode))

	return utils.compileFunction(
		"def makeRow(row):\n  return {%s}"%(", ".join(parts)), 
		"makeRow",
		locals())
	"""
    funcNs = globals().copy()
    funcNs["parent"] = parent
    funcNs.update(moreNames)
    if setupCode.strip():
        try:
            exec setupCode.rstrip() in funcNs
        except (SyntaxError, TypeError), ex:
            raise base.ui.logOldExc(base.BadCode(setupCode, "setup code", ex))
        except NameError, ex:
            raise base.ui.logOldExc(
                base.BadCode(
                    setupCode,
                    "setup code",
                    ex,
                    hint="This typically happens when you forget to put"
                    " quotes around string values."))
    return utils.compileFunction(code.rstrip(),
                                 funcName,
                                 funcNs,
                                 debug=base.DEBUG)


def _test():
    import doctest, rmkfuncs
    doctest.testmod(rmkfuncs)


if __name__ == "__main__":
    _test()