Esempio n. 1
0
def load_location_file(location_file, request):
    '''
        We would like to merge the current active model into the new model
        created by our location file prior to clearing our session
    '''
    if isdir(location_file):
        active_model = get_active_model(request)

        new_model = Model.load(location_file)
        new_model._cache.enabled = False

        if active_model is not None:
            active_model._map = new_model._map
            active_model._time_step = new_model._time_step
            active_model._num_time_steps = new_model._num_time_steps
            active_model.merge(new_model)
        else:
            active_model = new_model

        name = split(location_file)[1]
        if name != '':
            active_model.name = name

        init_session_objects(request, force=True)

        log.debug("model loaded - begin registering objects")

        RegisterObject(active_model, request)

        set_active_model(request, active_model.id)
Esempio n. 2
0
    def test_load_location_file(self, saveloc_, model):
        '''
        create a model
        load save file from script_boston which contains a spill. Then merge
        the created model into the model loaded from save file
        '''
        m = Model()
        m.environment += [Water(), constant_wind(1., 0.)]
        m.weatherers += Evaporation(m.environment[0], m.environment[-1])
        # has to have the same substance as the sample model
        m.spills += point_line_release_spill(10, (0, 0, 0),
                                             datetime(2014, 1, 1, 12, 0),
                                             substance=test_oil)

        # create save model
        sample_save_file = os.path.join(saveloc_, 'SampleSaveModel.zip')
        model.save(sample_save_file)

        if os.path.exists(sample_save_file):
            model = Model.load(sample_save_file)
            model.merge(m)

            for oc in m._oc_list:
                for item in getattr(m, oc):
                    model_oc = getattr(model, oc)
                    assert item is model_oc[item.id]

            for spill in m.spills:
                assert spill is model.spills[spill.id]

            # merge the other way and ensure model != m
            m.merge(model)
            assert model != m
Esempio n. 3
0
def upload_model(request):
    '''
        Uploads a new model in the form of a zipfile and registers it as the
        current active model.

        We are generating our own filename instead of trusting
        the incoming filename since that might result in insecure paths.

        We may want to eventually use something other than /tmp,
        and if you write to an untrusted location you will need to do
        some extra work to prevent symlink attacks.
    '''
    clean_session_dir(request)
    file_path, _name = process_upload(request, 'new_model')
    # Now that we have our file, we will now try to load the model into
    # memory.
    # Now that we have our file, is it a zipfile?
    if not is_savezip_valid(file_path):
        raise cors_response(
            request, HTTPBadRequest('Incoming file is not a '
                                    'valid zipfile!'))

    resp_msg = 'OK'
    # now we try to load our model from the zipfile.
    session_lock = acquire_session_lock(request)
    log.info('  session lock acquired (sess:{}, thr_id: {})'.format(
        id(session_lock),
        current_thread().ident))
    try:
        log.info('loading our model from zip...')
        init_session_objects(request, force=True)
        refs = get_session_objects(request)

        new_model = Model.load(file_path, refs=refs)
        new_model._cache.enabled = False

        new_model._schema.register_refs(new_model._schema(), new_model, refs)
        #         from ..views import implemented_types
        #
        #         RegisterObject(new_model, request, implemented_types)

        log.info('setting active model...')
        set_active_model(request, new_model.id)
    except Exception:
        raise cors_exception(request, HTTPBadRequest, with_stacktrace=True)
    finally:
        session_lock.release()
        log.info('  session lock released (sess:{}, thr_id: {})'.format(
            id(session_lock),
            current_thread().ident))

    # We will want to clean up our tempfile when we are done.
    os.remove(file_path)

    return cors_response(request, Response(resp_msg))
Esempio n. 4
0
def activate_uploaded_model(request):
    '''
        Activates a new model from a zipfile that is stored in the
        uploads folder, and registers it as the current active model.
    '''
    clean_session_dir(request)

    zipfile_path, _name = activate_uploaded(request)
    log.info('Model zipfile: {}'.format(zipfile_path))

    # Now that we have our file, we will now try to load the model into
    # memory.
    # Now that we have our file, is it a zipfile?
    if not is_savezip_valid(zipfile_path):
        raise cors_response(request,
                            HTTPBadRequest('File is not a valid zipfile!'))

    # now we try to load our model from the zipfile.
    session_lock = acquire_session_lock(request)
    log.info('  session lock acquired (sess:{}, thr_id: {})'.format(
        id(session_lock),
        current_thread().ident))
    try:
        log.info('Cargando nuestro modelo del zip...')
        init_session_objects(request, force=True)
        refs = get_session_objects(request)

        new_model = Model.load(zipfile_path, refs=refs)
        new_model._cache.enabled = False

        new_model._schema.register_refs(new_model._schema(), new_model, refs)
        #         from ..views import implemented_types

        #         RegisterObject(new_model, request, implemented_types)

        log.info('setting active model...')
        set_active_model(request, new_model.id)
    except Exception:
        raise cors_exception(request, HTTPBadRequest, with_stacktrace=True)
    finally:
        session_lock.release()
        log.info('  session lock released (sess:{}, thr_id: {})'.format(
            id(session_lock),
            current_thread().ident))

    # We will want to clean up our temporary zipfile when we are done.
    os.remove(zipfile_path)

    return cors_response(request, Response('OK'))
Esempio n. 5
0
def test_save_load_model(uncertain, zipsave, saveloc_):
    '''
    create a model, save it, then load it back up and check it is equal to
    original model
    '''
    model = make_model(uncertain)
    ice_mover = IceMover(testdata['IceMover']['ice_curr_curv'],
                         testdata['IceMover']['ice_top_curv'])
    model.movers += ice_mover
    model.outputters += IceJsonOutput([ice_mover])

    model.zipsave = zipsave

    print 'saving scenario to {}...'.format(saveloc_)
    _json_, savefile, _refs = model.save(saveloc_)

    print 'loading scenario ...'
    model2 = Model.load(savefile)

    assert model == model2
def test_save_load_model(uncertain, zipsave, saveloc_):
    '''
    create a model, save it, then load it back up and check it is equal to
    original model
    '''
    model = make_model(uncertain)
    ice_mover = IceMover(testdata['IceMover']['ice_curr_curv'],
                         testdata['IceMover']['ice_top_curv'])
    model.movers += ice_mover
    model.outputters += IceJsonOutput([ice_mover])

    model.zipsave = zipsave

    print 'saving scenario to {}...'.format(saveloc_)
    _json_, savefile, _refs = model.save(saveloc_)

    print 'loading scenario ...'
    model2 = Model.load(savefile)

    assert model == model2
Esempio n. 7
0
def test_location_file():
    '''
    Simple test to check if json_ contains nothing - default model is created
    '''
    model = Model.load('.', {'json_': 'save'})
    assert model == Model()