Пример #1
0
 def doInitialization(self):
     """ actually do the initialization and look up the models """
     if not self.initialized:
         parentModel = getModelByName(self.parentModelName)
         super(ModelCollectionManager, self).__init__(parentModel)
         for childName in self.childModelNames:
             childModel = getModelByName(childName)
             self.registerChildClass(childModel)
         self.initialized = True
Пример #2
0
 def doInitialization(self):
     """ actually do the initialization and look up the models """
     if not self.initialized:
         parentModel = getModelByName(self.parentModelName)
         super(ModelCollectionManager, self).__init__(parentModel)
         for childName in self.childModelNames:
             childModel = getModelByName(childName)
             self.registerChildClass(childModel)
         self.initialized = True
Пример #3
0
def get_channel_descriptions_json(request):
    """
    Returns a JsonResponse of the channel descriptions described by the model
    :param request: the request
    :param request.POST.model_name: the fully qualified name of the model
    :param request.POST.channel_name: (optional) the name of the channel
    :return: JsonResponse with the result.
    """
    if request.method == 'POST':
        try:
            model_name = request.POST.get('model_name', None)
            # model name is required
            if model_name:
                model = getModelByName(model_name)
                if model:
                    channel_name = request.POST.get('channel_name', None)
                    result = get_channel_descriptions(model, channel_name)
                    if result:
                        for key, value in result.iteritems():
                            if not isinstance(value, dict):
                                result[key] = value.__dict__
                        return JsonResponse(result)
                return JsonResponse({'error': 'bad parameters'}, status=204)
        except Exception as e:
            return HttpResponseNotAllowed(["POST"],
                                          content=traceback.format_exc())
    return HttpResponseForbidden()
Пример #4
0
 def do_initialization(self):
     """ actually do the initialization and look up the models """
     if not self.initialized:
         model_name = eval(self.model_name_variable)
         self.model = getModelByName(model_name)
         super(LazyQuerySet, self).__init__(self.model, self.initial_query, self.initial_using, self.initial_hints)
         self.initialized = True
Пример #5
0
def saveNewInstrumentData(request, instrumentName, jsonResult=False):
    errors = None
    if request.method == 'POST':
        form = BasaltInstrumentDataForm(request.POST, request.FILES)
        if form.is_valid():
            if request.user.is_authenticated():
                user = request.user
            else:
                user = None
            instrument = form.cleaned_data["instrument"]
            messages.success(request, 'Instrument data is successfully saved.' )
            importFxn = lookupImportFunctionByName(settings.XGDS_INSTRUMENT_IMPORT_MODULE_PATH, 
                                                   instrument.dataImportFunctionName)
            object_id = None
            if 'object_id' in request.POST:
                object_id = int(request.POST['object_id'])
            result = importFxn(instrument=instrument, 
                               portableDataFile=request.FILES.get("portableDataFile", None),
                               manufacturerDataFile=request.FILES.get("manufacturerDataFile", None),
                               utcStamp=form.cleaned_data["dataCollectionTime"], 
                               timezone=form.getTimezone(), 
                               vehicle=form.getVehicle(),
                               name=form.cleaned_data['name'],
                               description=form.cleaned_data['description'],
                               minerals=form.cleaned_data['minerals'],
                               user=user,
                               latitude=form.cleaned_data['lat'],
                               longitude=form.cleaned_data['lon'],
                               altitude=form.cleaned_data['alt'],
                               collector=form.cleaned_data['collector'],
                               object_id=object_id)
            if result['status'] == 'success':
                if 'relay' in request.POST:
                    theModel = getModelByName(settings.XGDS_MAP_SERVER_JS_MAP[result['modelName']]['model'])
                    theInstance = theModel.objects.get(pk=result['pk'])
                    deletePostKey(request.POST, 'relay')
                    addRelay(theInstance, request.FILES, json.dumps(request.POST), request.get_full_path())

                if jsonResult:
                    return HttpResponse(json.dumps(result), content_type='application/json')
                else:
                    return HttpResponseRedirect(reverse('search_map_single_object', kwargs={'modelPK':result['pk'],
                                                                                            'modelName':result['modelName']}))
            else:
                errors = result['message']
        else:
            errors = str(form.errors)
            print 'form errors in receiving instrument data'
        
        if jsonResult:
            return HttpResponse(json.dumps({'status': 'error', 'message': errors}), content_type='application/json', status=httplib.NOT_ACCEPTABLE)
        else:
            messages.error(request, 'Errors %s' % errors)
            return render(request,
                          'xgds_instrument/importBasaltInstrumentData.html',
                          {'form': form,
                           'errors': form.errors,
                           'instrumentDataImportUrl': reverse('save_instrument_data', kwargs={'instrumentName': instrumentName}),
                           'instrumentType': instrumentName},
                          status=httplib.NOT_ACCEPTABLE)      
Пример #6
0
    def do_initialization(self):
        """ actually do the initialization and look up the models """
        if not self.initialized:
            model_name = eval(self.model_name_variable)
            self.model = getModelByName(model_name)
            super(LazyModelManager, self).__init__()

            self.initialized = True
Пример #7
0
    def __init__(self, meta):
        self.model = getModelByName(meta['queryModel'])

        self.timestampField = meta['queryTimestampField']
        self.timestampMicrosecondsField = meta.get('queryTimestampMicrosecondsField', None)
        self.timestampNanosecondsField = meta.get('queryTimestampNanosecondsField', None)
        self.startTime = meta.get('startTime', None)
        self.endTime = meta.get('endTime', None)

        self.filterDict = dict(meta.get('queryFilter', []))
        self.queryTopic = meta['queryModel']
        queryFilter = meta.get('queryFilter', [])
        for _field, value in queryFilter:
            self.queryTopic += '.%s' % value
        self.queryTopic += ':'
Пример #8
0
    def __init__(self, meta):
        self.model = getModelByName(meta['queryModel'])

        self.timestampField = meta['queryTimestampField']
        self.timestampMicrosecondsField = meta.get(
            'queryTimestampMicrosecondsField', None)
        self.timestampNanosecondsField = meta.get(
            'queryTimestampNanosecondsField', None)
        self.startTime = meta.get('startTime', None)
        self.endTime = meta.get('endTime', None)

        self.filterDict = dict(meta.get('queryFilter', []))
        self.queryTopic = meta['queryModel']
        queryFilter = meta.get('queryFilter', [])
        for _field, value in queryFilter:
            self.queryTopic += '.%s' % value
        self.queryTopic += ':'
Пример #9
0
def unravel_post(post_dict):
    """
    Read the useful contents of the post dictionary
    :param post_dict:
    :return: the PostData properly filled out
    """
    class PostData(object):
        model = None
        channel_names = None
        flight_ids = None
        start_time = None
        end_time = None
        filter_dict = None
        time = None
        downsample = None

    result = PostData()
    model_name = post_dict.get('model_name', None)
    # model name is required
    if model_name:
        result.model = getModelByName(model_name)
    result.channel_names = post_dict.getlist('channel_names', None)
    if 'flight_ids' in post_dict:
        result.flight_ids = post_dict.getlist('flight_ids', None)
    elif 'flight_ids[]' in post_dict:
        result.flight_ids = post_dict.getlist('flight_ids[]', None)
    start_time_string = post_dict.get('start_time', None)
    if start_time_string:
        result.start_time = dateparser(start_time_string)
    end_time_string = post_dict.get('end_time', None)
    if end_time_string:
        result.end_time = dateparser(end_time_string)
    time_string = post_dict.get('time', None)
    if time_string:
        result.time = dateparser(time_string)

    filter_json = post_dict.get('filter', None)
    if filter_json:
        result.filter_dict = json.loads(filter_json)

    result.downsample = post_dict.get('downsample', None)
    if result.downsample is not None:
        result.downsample = int(result.downsample)

    return result
Пример #10
0
    def __init__(self, options):

        ensure_vehicle(options)
        patch_yaml_path(options)

        # Create a CsvImporter object with no corresponding CSV file:
        self.importer = self.construct_importer(options)
        self.keys = self.importer.config['fields'].keys()
        self.delimiter = self.importer.config['delimiter']
        self.model = getModelByName(self.importer.config['class'])
        if 'verbose' in options:
            self.verbose = options['verbose']
        else:
            self.verbose = False
        self.needs_flight = False
        if hasattr(self.model(), 'flight'):
            self.needs_flight = True
        super(CsvSaver, self).__init__(options)
Пример #11
0
def initProfiles():
    for profileMeta in settings.XGDS_PLOT_PROFILES:
        profile = Profile()
        profile.valueField = profileMeta['valueField']
        profile.valueCode = profile.valueField
        profile.model = getModelByName(profileMeta['queryModel'])
        profile.timestampField = profileMeta['queryTimestampField']
        profile.zField = profileMeta['queryZField']
        profile.filter = profileMeta['queryFilter']

        fields = profile.model._meta._field_name_cache
        fieldLookup = dict([(f.name, f) for f in fields])
        profile.name = firstcaps(fieldLookup[profile.valueField].verbose_name)
        profile.timeLabel = firstcaps(fieldLookup[profile.timestampField].verbose_name)
        profile.zLabel = firstcaps(fieldLookup[profile.zField].verbose_name)

        PROFILES.append(profile)
        PROFILE_LOOKUP[profile.valueField] = profile
Пример #12
0
    def importPlan(cls, name, buf, meta, planSchema=None, path=None):
        PLAN_MODEL = getModelByName(settings.XGDS_PLANNER_PLAN_MODEL)
        importer = cls()

        meta.setdefault('name', name)

        if not planSchema:
            try:
                wholePlatform = meta['platform']
                planSchema = models.getPlanSchema(wholePlatform.name)
            except:  # pylint: disable=W0702
                # bad news
                print "no platform, you need to pass the plan Schema" + name
                return
        importer.setDefaultMeta(meta, path, planSchema)
        planDoc = importer.importPlanFromBuffer(buf, meta, planSchema)

        dbPlan = PLAN_MODEL()

        dbPlan.jsonPlan = xpjson.dumpDocumentToDotDict(planDoc)
        dbPlan.extractFromJson(overWriteDateModified=False)

        return dbPlan
Пример #13
0
    def importPlan(cls, name, buf, meta, planSchema=None, path=None):
        PLAN_MODEL = getModelByName(settings.XGDS_PLANNER2_PLAN_MODEL)
        importer = cls()

        meta.setdefault('name', name)

        if not planSchema:
            try:
                wholePlatform = meta['platform']
                planSchema = models.getPlanSchema(wholePlatform.name)
            except:  # pylint: disable=W0702
                # bad news
                print "no platform, you need to pass the plan Schema" + name
                return
        importer.setDefaultMeta(meta, path, planSchema)

        planDoc = importer.importPlanFromBuffer(buf, meta, planSchema)

        dbPlan = PLAN_MODEL()

        dbPlan.jsonPlan = xpjson.dumpDocumentToDotDict(planDoc)
        dbPlan.extractFromJson(overWriteDateModified=False)
        
        return dbPlan