Exemple #1
0
def get_environment(request):
    '''Returns an Gnome Environment object in JSON.'''
    content_requested = request.matchdict.get('obj_id')
    resp = Response(content_type='arraybuffer')
    route = content_requested[1] if len(content_requested) > 1 else None
    if (len(content_requested) > 1):
        if route == 'grid':
            resp.body = get_grid(request)
            resp.headers.add('content-encoding', 'deflate')
            return cors_response(request, resp)
        if route == 'vectors':
            resp.body, dshape = get_vector_data(request)
            resp.headers.add('content-encoding', 'deflate')
            resp.headers.add('Access-Control-Expose-Headers', 'shape')
            resp.headers.add('shape', str(dshape))
            return cors_response(request, resp)
        if route == 'nodes':
            resp.body = get_nodes(request)
            resp.headers.add('content-encoding', 'deflate')
            return cors_response(request, resp)
        if route == 'centers':
            resp.body = get_centers(request)
            resp.headers.add('content-encoding', 'deflate')
            return cors_response(request, resp)
        if route == 'metadata':
            return get_metadata(request)
    else:
        return get_object(request, implemented_types)
def upload_environment(request):
    switch_to_existing_session(request)
    log_prefix = 'req({0}): upload_environment():'.format(id(request))
    log.info('>>{}'.format(log_prefix))


    file_list = request.POST['file_list']
    file_list = ujson.loads(file_list)
    name = request.POST['name']
    file_name = file_list[0]

    log.info('  {} file_name: {}, name: {}'
             .format(log_prefix, file_name, name))

    env_type = request.POST.get('obj_type', [])
    request.body = ujson.dumps({'obj_type': env_type,
                                'filename': file_name,
                                'name': name
                                }).encode('utf-8')

    env_obj = create_environment(request)
    resp = Response(ujson.dumps(env_obj))

    log.info('<<{}'.format(log_prefix))
    return cors_response(request, resp)
Exemple #3
0
def upload_map(request):
    log_prefix = 'req({0}): upload_map():'.format(id(request))
    log.info('>>{}'.format(log_prefix))

    file_list = request.POST['file_list']
    file_list = ujson.loads(file_list)
    name = request.POST['name']
    file_name = file_list[0]

    log.info('  {} file_name: {}, name: {}'.format(log_prefix, file_name,
                                                   name))

    # fixme: why is this not just calling the pygnome code directly?
    request.body = ujson.dumps({
        'obj_type': 'gnome.maps.map.MapFromBNA',
        'filename': file_name,
        'refloat_halflife': 6.0,
        'name': name
    }).encode('utf-8')

    map_obj = create_map(request)
    resp = Response(ujson.dumps(map_obj))

    log.info('<<{}'.format(log_prefix))
    return cors_response(request, resp)
Exemple #4
0
def upload_release(request):
    switch_to_existing_session(request)
    log_prefix = 'req({0}): upload_release():'.format(id(request))
    log.info('>>{}'.format(log_prefix))

    file_list = request.POST.pop('file_list')
    file_list = ujson.loads(file_list)
    name = request.POST.pop('name')
    file_name = file_list

    log.info('  {} file_name: {}, name: {}'.format(log_prefix, file_name,
                                                   name))

    release_type = request.POST.pop('obj_type', [])

    release_json = {
        'obj_type': release_type,
        'filename': file_name,
        'name': name
    }

    release_json.update(request.POST)
    release_json.pop('session')

    request.body = ujson.dumps(release_json).encode('utf-8')

    release_obj = create_release(request)
    resp = Response(ujson.dumps(release_obj))

    log.info('<<{}'.format(log_prefix))
    return cors_response(request, resp)
Exemple #5
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 = 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!'))

    # now we try to load our model from the zipfile.
    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('semaphore acquired.')
    try:
        log.info('loading our model from zip...')
        new_model = load(file_path)
        new_model._cache.enabled = False

        init_session_objects(request, force=True)

        RegisterObject(new_model, request)

        log.info('setting active model...')
        set_active_model(request, new_model.id)
    except:
        raise cors_exception(request, HTTPBadRequest, with_stacktrace=True)
    finally:
        gnome_sema.release()
        log.info('semaphore released.')

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

    return cors_response(request, Response('OK'))
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 = 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!'))

    # now we try to load our model from the zipfile.
    gnome_sema = request.registry.settings['py_gnome_semaphore']
    gnome_sema.acquire()
    log.info('semaphore acquired.')
    try:
        log.info('loading our model from zip...')
        new_model = load(file_path)
        new_model._cache.enabled = False

        init_session_objects(request, force=True)

        RegisterObject(new_model, request)

        log.info('setting active model...')
        set_active_model(request, new_model.id)
    except:
        raise cors_exception(request, HTTPBadRequest, with_stacktrace=True)
    finally:
        gnome_sema.release()
        log.info('semaphore released.')

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

    return cors_response(request, Response('OK'))
Exemple #7
0
def get_release(request):
    '''Returns an Gnome Release object in JSON.'''
    content_requested = request.matchdict.get('obj_id')
    resp = Response(content_type='arraybuffer', content_encoding='deflate')
    route = content_requested[1] if len(content_requested) > 1 else None
    if (len(content_requested) > 1):
        if route == 'start_positions':
            resp.body = get_start_positions(request)
            return cors_response(request, resp)
        if route == 'polygons':
            resp.body, num_lengths = get_polygons(request)
            resp.headers.add('Access-Control-Expose-Headers', 'num_lengths')
            resp.headers.add('num_lengths', str(num_lengths))
            return cors_response(request, resp)
        if route == 'metadata':
            return get_metadata(request)
    else:
        return get_object(request, implemented_types)
Exemple #8
0
def download_file(request):
    log_prefix = 'req({0}): download_file():'.format(id(request))
    log.info('>>' + log_prefix)

    session_path = get_session_dir(request)
    file_path = sep.join(map(str, request.matchdict['file_path']))
    output_path = join(session_path, file_path)

    log.info('  {} output_path: {}'.format(log_prefix, output_path))

    try:
        model_name = get_active_model(request).name
    except Exception:
        raise cors_response(request, HTTPNotFound('No Active Model!'))

    if isdir(output_path):
        short_dirname = basename(output_path).split('.')[-1]
        output_zip_path = "{0}_{1}.zip".format(model_name, short_dirname)
        zip_path = join(output_path, output_zip_path)
        zf = zipfile.ZipFile(zip_path, "w")

        for dirname, _subdirs, files in walk(output_path):
            for filename in files:
                if (not filename.endswith(output_zip_path)
                        and not isdir(filename)):
                    zipfile_path = join(dirname, filename)
                    zf.write(zipfile_path, basename(zipfile_path))

        zf.close()

        response = FileResponse(zip_path, request)
        response.headers['Content-Disposition'] = (
            "attachment; filename={0}".format(basename(zip_path)))
        log.info('<<' + log_prefix)
        return response
    elif isfile(output_path):
        log.info('<<' + log_prefix)

        return FileResponse(output_path, request)
    else:
        raise cors_response(
            request,
            HTTPNotFound('File(s) requested do not '
                         'exist on the server!'))
Exemple #9
0
def upload_map(request):
    file_path = process_upload(request, 'new_map').split(os.path.sep)[-1]
    request.body = ujson.dumps({'obj_type': 'gnome.map.MapFromBNA',
                                'filename': file_path,
                                'refloat_halflife': 6.0,
                                'json_': 'webapi'
                                })
    map_obj = create_map(request)
    resp = Response(ujson.dumps(map_obj))

    return cors_response(request, resp)
Exemple #10
0
def upload_map(request):
    file_path = process_upload(request, 'new_map').split(os.path.sep)[-1]
    request.body = ujson.dumps({
        'obj_type': 'gnome.map.MapFromBNA',
        'filename': file_path,
        'refloat_halflife': 6.0,
        'json_': 'webapi'
    })
    map_obj = create_map(request)
    resp = Response(ujson.dumps(map_obj))

    return cors_response(request, resp)
Exemple #11
0
def activate_environment(request):
    '''
        Activate an environment file that has already been persistently
        uploaded.
    '''
    log_prefix = 'req({0}): activate_environment():'.format(id(request))
    log.info('>>{}'.format(log_prefix))

    file_name, name = activate_uploaded(request)
    resp = Response(ujson.dumps({'filename': file_name, 'name': name}))

    log.info('<<{}'.format(log_prefix))
    return cors_response(request, resp)
Exemple #12
0
def get_map(request):
    '''Returns a Gnome Map object in JSON.'''
    content_requested = request.matchdict.get('obj_id')
    resp = Response(content_type='arraybuffer', content_encoding='deflate')
    route = content_requested[1] if len(content_requested) > 1 else None
    if (len(content_requested) > 1):
        if route == 'raster':
            resp.body, shape, bbox = get_raster(request)
            resp.headers.add('Access-Control-Expose-Headers', 'shape')
            resp.headers.add('Access-Control-Expose-Headers', 'bbox')
            resp.headers.add('shape', str(shape))
            resp.headers.add('bbox', str(bbox))
            return cors_response(request, resp)
        if route == 'geojson':
            return get_geojson(request, implemented_types)
    else:
        return get_object(request, implemented_types)
def get_output_file(request):
    log_prefix = 'req{0}: get_output_file()'.format(id(request))
    log.info('>>' + log_prefix)
    session_path = get_session_dir(request)
    filename = request.GET.get('filename')
    if filename:
        output_path = os.path.join(session_path, filename)

        response = FileResponse(output_path, request)
        response.headers['Content-Disposition'] = (
            "attachment; filename={0}".format(os.path.basename(output_path)))
        log.info('<<' + log_prefix)
        return response
    else:
        raise cors_response(
            request,
            HTTPNotFound('File(s) requested do not '
                         'exist on the server!'))
Exemple #14
0
def activate_map(request):
    '''
        Activate a map that has already been persistently uploaded.
    '''
    log_prefix = 'req({0}): activate_map():'.format(id(request))
    log.info('>>{}'.format(log_prefix))

    file_name, name = activate_uploaded(request)
    file_path = file_name.split(os.path.sep)[-1]

    request.body = ujson.dumps({
        'obj_type': 'gnome.maps.map.MapFromBNA',
        'filename': file_path,
        'refloat_halflife': 6.0,
        'name': name
    }).encode('utf-8')

    map_obj = create_map(request)
    resp = Response(ujson.dumps(map_obj))

    log.info('<<{}'.format(log_prefix))
    return cors_response(request, resp)
Exemple #15
0
def download_model(request):
    '''
        Here is where we save the active model as a zipfile and
        download it to the client
    '''
    my_model = get_active_model(request)

    if my_model:
        tf = tempfile.NamedTemporaryFile()
        dir_name, base_name = os.path.split(tf.name)

        my_model.save(saveloc=dir_name, name=base_name)
        response_filename = ('{0}.zip'.format(my_model.name))

        tf.seek(0)

        response = request.response
        response.content_type = 'application/zip'
        response.content_disposition = ('attachment; filename={0}'
                                        .format(response_filename))
        response.app_iter = FileIter(tf)
        return response
    else:
        raise cors_response(request, HTTPNotFound('No Active Model!'))
Exemple #16
0
def download_model(request):
    '''
        Here is where we save the active model as a zipfile and
        download it to the client
    '''
    my_model = get_active_model(request)

    if my_model:
        tf = tempfile.NamedTemporaryFile()
        dir_name, base_name = os.path.split(tf.name)

        my_model.save(saveloc=dir_name, name=base_name)
        response_filename = ('{0}.zip'.format(my_model.name))

        tf.seek(0)

        response = request.response
        response.content_type = 'application/zip'
        response.content_disposition = (
            'attachment; filename={0}'.format(response_filename))
        response.app_iter = FileIter(tf)
        return response
    else:
        raise cors_response(request, HTTPNotFound('No Active Model!'))
Exemple #17
0
def activate_map_options(request):
    return cors_response(request, request.response)
Exemple #18
0
def mover_upload_options(request):
    return cors_response(request, request.response)
Exemple #19
0
def upload_map_options(request):
    return cors_response(request, request.response)
Exemple #20
0
def environment_upload(request):
    filename, name = process_upload(request, 'new_environment')
    resp = Response(ujson.dumps({'filename': filename, 'name': name}))

    return cors_response(request, resp)
Exemple #21
0
def environment_upload_options(request):
    return cors_response(request, request.response)
Exemple #22
0
def upload_mover(request):
    file_path = process_upload(request, 'new_mover')
    resp = Response(ujson.dumps({'filename': file_path}))

    return cors_response(request, resp)
Exemple #23
0
def activate_environment_options(request):
    return cors_response(request, request.response)
def environment_upload(request):
    filename = process_upload(request, "new_environment")
    resp = Response(ujson.dumps({"filename": filename}))

    return cors_response(request, resp)
Exemple #25
0
def upload_mover(request):
    file_path = process_upload(request, 'new_mover')
    resp = Response(ujson.dumps({'filename': file_path}))

    return cors_response(request, resp)
Exemple #26
0
def mover_upload_options(request):
    return cors_response(request, request.response)
Exemple #27
0
def upload_model_options(request):
    return cors_response(request, request.response)
def environment_upload_options(request):
    return cors_response(request, request.response)
Exemple #29
0
def release_upload_options(request):
    return cors_response(request, request.response)