示例#1
0
 def to_python(self, value):
     ''' Takes json string from database and builds a DotDict structure
     '''
     if value == '':
         return DotDict()
     elif type(value) == DotDict:
         return value
     else:
         theDotDict = DotDict()
         try:
             jsonStruct = json.loads(value)
             theDotDict = convertToDotDictRecurse(jsonStruct)
             assert isinstance(
                 theDotDict,
                 DotDict), 'expected a DotDict object, found a %s' % type(
                     theDotDict).__name__
             for key in theDotDict.iterkeys():
                 assert type(key) in (
                     unicode, str
                 ), 'expected unicode or str keys, found a %s' % type(
                     key).__name__
         except (ValueError, AssertionError), e:
             #print 'problem with json for %s ' % (value)
             raise ValidationError(
                 'Invalid JSON data in ExtrasDotField: %s' % e)
         return theDotDict
示例#2
0
 def exportPlan(self, plan, schema):
     # plan = copy.deepcopy(plan)
     context = DotDict({
         'plan': plan
     })
     context.schema = schema
     self.initPlan(plan, context)
     return self.exportPlanInternal(plan, context)
示例#3
0
def transformTopDown(obj, func):
    if isinstance(obj, (list, tuple)):
        return [transformTopDown(v, func) for v in obj]
    elif isinstance(obj, (int, float, str, unicode, bool, long)) or obj is None:
        return obj
    else:
        return DotDict(((k, transformTopDown(v, func))
                     for k, v in func(obj).iteritems()))
示例#4
0
 def to_python(self, value):
     ''' Takes json string from database and builds a DotDict structure
     '''
     if value == '':
         return DotDict()
     elif type(value) == DotDict:
         return value
     else:
         theDotDict = DotDict()
         try:
             jsonStruct = json.loads(value)
             theDotDict = convertToDotDictRecurse(jsonStruct)
             assert isinstance(theDotDict, DotDict), 'expected a DotDict object, found a %s' % type(theDotDict).__name__
             for key in theDotDict.iterkeys():
                 assert type(key) in (unicode, str), 'expected unicode or str keys, found a %s' % type(key).__name__
         except (ValueError, AssertionError), e:
             raise ValidationError('Invalid JSON data in ExtrasDotField: %s' % e)
         return theDotDict
示例#5
0
def resolveInheritanceLookup(spec,
                             parentSpecLookup,
                             inheritFields=(),
                             localOnlyFields=()):
    if 'parent' in spec:
        parent = parentSpecLookup.get(spec.parent)
        if parent:
            result = (DotDict(
                InheritDict(spec,
                            parent,
                            inheritFields=inheritFields,
                            localOnlyFields=localOnlyFields)))
            result.pop('parent', None)
            return result
        else:
            raise UnknownParentError(spec.parent)
    else:
        return spec
示例#6
0
def resolveSchemaInheritance(schemaDict):
    # resolve inheritance in paramSpecs
    rawParamSpecs = schemaDict.get('paramSpecs', [])
    paramSpecLookup = resolveSpecInheritance(rawParamSpecs)

    # resolve inheritance in commandSpecs
    rawCommandSpecs = schemaDict.get('commandSpecs', [])
    rawCommandSpecs.append(
        DotDict({
            'type': 'CommandSpec',
            'id': 'Command',
            'abstract': True,
        }))
    commandSpecsLookup = resolveSpecInheritance(rawCommandSpecs,
                                                inheritFields=('params'),
                                                localOnlyFields=('id', 'name',
                                                                 'abstract'))

    # filter out abstract commandSpecs
    commandSpecs = [
        commandSpecsLookup[spec.id] for spec in rawCommandSpecs
        if not spec.get('abstract', False)
    ]

    # abstract field no longer needed
    for c in commandSpecs:
        c.pop('abstract', None)

    # resolve inheritance of ParamSpecs found in params field of commandSpecs
    for c in commandSpecs:
        c.params = [
            resolveInheritanceLookup(p, paramSpecLookup)
            for p in c.get('params', [])
        ]

    for f in ('planParams', 'stationParams', 'segmentParams', 'targetParams'):
        schemaDict[f] = [
            resolveInheritanceLookup(p, paramSpecLookup)
            for p in schemaDict.get(f, [])
        ]

    if not KEEP_PARAM_SPECS:
        schemaDict.pop('paramSpecs', None)
    schemaDict.commandSpecs = commandSpecs
示例#7
0
def planExport(request, uuid, name, time=None, outputDirectory=None, isAjax=False):
    """
    Normally plan export urls are built up by the planExporter.url
    but some exporters (pml) can take a time.
    """
    dbPlan = getDbPlan(uuid)

    formatCode = request.GET.get('format')
    if formatCode is not None:
        # user explicitly specified e.g. '?format=kml'
        exporterClass = choosePlanExporter.PLAN_EXPORTERS_BY_FORMAT.get(formatCode)
        if exporterClass is None:
            return HttpResponseBadRequest('invalid export format %s' % formatCode)
    else:
        # filename ends with e.g. '.kml'
        exporterClass = None
        for entry in choosePlanExporter.PLAN_EXPORTERS:
            if name.endswith(entry.extension):
                exporterClass = entry.exporterClass
        if exporterClass is None:
            return HttpResponseBadRequest('could not infer export format to use: "format" query parameter not set and extension not recognized for filename "%s"' % name)

    exporter = exporterClass()
    if time:
        try:
            thetime = dateparser(time)
            context = DotDict({'startTime': thetime.astimezone(pytz.utc)})
            exporter.initPlan(dbPlan, context)
        except:
            pass
        
    if outputDirectory:
        # output the exported file to a directory
        exporter.exportDbPlanToPath(dbPlan, os.path.join(outputDirectory, name))
        return True
    elif not isAjax:
        return exporter.getHttpResponse(dbPlan, attachmentName=name)
    else:
        return exporter.getHttpResponse(dbPlan, attachmentName=None)
示例#8
0
 def exportPlan(self, plan, schema):
     context = DotDict({'plan': plan})
     context.schema = schema
     self.initPlan(plan, context)
     return self.exportPlanInternal(plan, context)
示例#9
0
 def __init__(self, *args, **kwargsin):
     kwargs = dict(blank=True)
     if "default" not in kwargsin:
         kwargs["default"] = DotDict()
     kwargs.update(**kwargsin)
     super(ExtrasDotField, self).__init__(*args, **kwargs)