Exemplo n.º 1
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([("Content-description", "dods_form"), ("Content-type", "text/html; charset=utf-8")])

        # our default environment; we need to include the base template from
        # pydap as well since our template extends it
        self.loaders = [PackageLoader("pydap.responses.html", "templates"), PackageLoader("pydap.wsgi", "templates")]
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_matlab'),
         ('Content-type', 'application/x-matlab'),
         #('Content-description', 'dods_matlab'),
         #('Content-type', 'text/plain; charset=ascii'),
     ])
Exemplo n.º 3
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([('Content-description', 'dods_data'),
                             ('Content-type', 'application/octet-stream')])

        length = calculate_size(dataset)
        if length is not None:
            self.headers.append(('Content-length', str(length)))
Exemplo n.º 4
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([('Content-description', 'dods_data'),
                             ('Content-type', 'application/octet-stream')])

        length = calculate_size(dataset)
        if length is not None:
            self.headers.append(('Content-length', str(length)))
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([
            ("Content-description", "dods_form"),
            ("Content-type", "text/plain; charset=utf-8"),
        ])

        # our default environment;
        self.loaders = [
            PackageLoader("pydap.responses.html", "templates"),
        ]
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([
            ("Content-description", "dods_form"),
            ("Content-type", "text/plain; charset=utf-8"),
        ])

        # our default environment;
        self.loaders = [
            PackageLoader("pydap.responses.html", "templates"),
        ]
Exemplo n.º 7
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([
            ('Content-description', 'dods_dds'),
            ('Content-type', 'text/plain; charset=utf-8'),

            # CORS
            ('Access-Control-Allow-Origin', '*'),
            ('Access-Control-Allow-Headers',
                'Origin, X-Requested-With, Content-Type'),
        ])
Exemplo n.º 8
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([
            ("Content-description", "dods_form"),
            ("Content-type", "text/html; charset=utf-8"),
        ])

        # our default environment; we need to include the base template from
        # pydap as well since our template extends it
        self.loaders = [
            PackageLoader("pydap.responses.html", "templates"),
            PackageLoader("pydap.wsgi", "templates"),
        ]
Exemplo n.º 9
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)
        self.headers.extend([
            ('Content-description', 'dods_data'),
            ('Content-type', 'application/octet-stream'),

            # CORS
            ('Access-Control-Allow-Origin', '*'),
            ('Access-Control-Allow-Headers',
                'Origin, X-Requested-With, Content-Type'),
        ])

        length = calculate_size(dataset)
        if length is not None:
            self.headers.append(('Content-length', length))
Exemplo n.º 10
0
    def __call__(self, environ, start_response):
        def serialize(dataset):
            location = construct_url(environ, with_query_string=False)
            base = location[:location.rfind('/')]
            context = {
                'root':
                construct_url(environ,
                              with_query_string=False,
                              with_path_info=False,
                              script_name='').rstrip('/'),
                'base':
                base,
                'location':
                location,
                'version':
                '.'.join(str(d) for d in __version__),
            }
            renderer = environ.get('pydap.renderer', self.renderer)
            template = renderer.loader('help.html')
            output = renderer.render(template,
                                     context,
                                     output_format='text/html')
            if hasattr(dataset, 'close'): dataset.close()
            return [output]

        self.serialize = serialize
        return BaseResponse.__call__(self, environ, start_response)
Exemplo n.º 11
0
 def __call__(self, environ, start_response):
     def serialize(dataset):
         location = construct_url(environ, with_query_string=False)
         base = location[:location.rfind('/')]
         context = {
             'root': construct_url(environ, with_query_string=False, with_path_info=False, script_name='').rstrip('/'),
             'base': base,
             'location': location,
             'version' : '.'.join(str(d) for d in __version__),
         }
         renderer = environ.get('pydap.renderer', self.renderer)
         template = renderer.loader('help.html')
         output = renderer.render(template, context, output_format='text/html')
         if hasattr(dataset, 'close'): dataset.close()
         return [output]
     self.serialize = serialize
     return BaseResponse.__call__(self, environ, start_response)
Exemplo n.º 12
0
    def __call__(self, environ, start_response):
        # If we came from a post, parse response and redirect to ascii.
        if environ["REQUEST_METHOD"] == "POST":
            # Parse POST and redirect to proper response.
            form = parse_formvars(environ)
            projection, selection = [], []
            for k in form:
                # Selection.
                if k.startswith("var1") and form[k] != "--":
                    name = k[5:]
                    sel = "%s%s%s" % (form[k], form["op_%s" % name], form["var2_%s" % name])
                    selection.append(sel)
                # Projection.
                if form[k] == "on":
                    var = [k]
                    i = 0
                    while "%s[%d]" % (k, i) in form:
                        var.append("[%s]" % form["%s[%d]" % (k, i)])
                        i += 1
                    var = "".join(var)
                    if var not in projection:
                        projection.append(var)

            projection = ",".join(projection)
            selection = "&".join(selection)
            query = projection + "&" + selection

            # Get current location.
            location = construct_url(environ, with_query_string=False)

            # Empty queries SHOULD NOT return everything, because this
            # means the user didn't select any variables.
            if not query.rstrip("?&"):
                app = HTTPBadRequest("You did not select any variables.")
            else:
                # Replace html extension for ascii and redirect.
                response = form["response"]
                redirect = "%s.%s?%s" % (location[:-5], response, query)
                app = HTTPSeeOther(redirect)
            return app(environ, start_response)
        else:
            self.serialize = self._render(environ)
            return BaseResponse.__call__(self, environ, start_response)
Exemplo n.º 13
0
    def __call__(self, environ, start_response):
        # If we came from a post, parse response and redirect to ascii.
        if environ['REQUEST_METHOD'] == 'POST':
            # Parse POST and redirect to proper response.
            form = parse_formvars(environ)
            projection, selection = [], []
            for k in form:
                # Selection.
                if k.startswith('var1') and form[k] != '--':
                    name = k[5:]
                    sel = '%s%s%s' % (form[k], form['op_%s' % name], form['var2_%s' % name])
                    selection.append(sel)
                # Projection.
                if form[k] == 'on':
                    var = [k]
                    i = 0
                    while '%s[%d]' % (k, i) in form:
                        var.append('[%s]' % form[ '%s[%d]' % (k, i) ])
                        i += 1
                    var = ''.join(var)
                    if var not in projection:
                        projection.append(var)

            projection = ','.join(projection)
            selection = '&'.join(selection)
            query = projection + '&' + selection
            
            # Get current location.
            location = construct_url(environ, with_query_string=False)

            # Empty queries SHOULD NOT return everything, because this
            # means the user didn't select any variables.
            if not query.rstrip('?&'):
                app = HTTPBadRequest('You did not select any variables.')
            else:
                # Replace html extension for ascii and redirect.
                response = form['response']
                redirect = '%s.%s?%s' % (location[:-5], response, query)
                app = HTTPSeeOther(redirect)
            return app(environ, start_response)
        else:
            self.serialize = self._render(environ)
            return BaseResponse.__call__(self, environ, start_response)
Exemplo n.º 14
0
    def __call__(self, environ, start_response):
        # Create a Beaker cache dependent on the query string, since
        # most (all?) pre-computed values will depend on the specific
        # dataset. We strip all WMS related arguments since they don't
        # affect the dataset.
        query = parse_dict_querystring(environ)
        try:
            dap_query = [
                '%s=%s' % (k, query[k]) for k in query
                if k.lower() not in WMS_ARGUMENTS
            ]
            dap_query = [pair.rstrip('=') for pair in dap_query]
            dap_query.sort()  # sort for uniqueness
            dap_query = '&'.join(dap_query)
            location = construct_url(environ,
                                     with_query_string=True,
                                     querystring=dap_query)
            self.cache = environ['beaker.cache'].get_cache(
                'pydap.responses.wms+' + location)
        except KeyError:
            self.cache = None

        # Handle GetMap and GetCapabilities requests
        type_ = query.get('REQUEST', 'GetMap')
        if type_ == 'GetCapabilities':
            self.serialize = self._get_capabilities(environ)
            self.headers.append(('Content-type', 'text/xml'))
            self.headers.append(('Access-Control-Allow-Origin', '*'))
        elif type_ == 'GetMap':
            self.serialize = self._get_map(environ)
            self.headers.append(('Content-type', 'image/png'))
        elif type_ == 'GetColorbar':
            self.serialize = self._get_colorbar(environ)
            self.headers.append(('Content-type', 'image/png'))
        else:
            raise HTTPBadRequest('Invalid REQUEST "%s"' % type_)

        return BaseResponse.__call__(self, environ, start_response)
Exemplo n.º 15
0
    def __call__(self, environ, start_response):
        # Create a Beaker cache dependent on the query string, since
        # most (all?) pre-computed values will depend on the specific
        # dataset. We strip all WMS related arguments since they don't
        # affect the dataset.
        query = parse_dict_querystring(environ)
        try:
            dap_query = ['%s=%s' % (k, query[k]) for k in query
                    if k.lower() not in WMS_ARGUMENTS]
            dap_query = [pair.rstrip('=') for pair in dap_query]
            dap_query.sort()  # sort for uniqueness
            dap_query = '&'.join(dap_query)
            location = construct_url(environ,
                    with_query_string=True,
                    querystring=dap_query)
            self.cache = environ['beaker.cache'].get_cache(
                    'pydap.responses.wms+' + location)
        except KeyError:
            self.cache = None

        # Handle GetMap and GetCapabilities requests
        type_ = query.get('REQUEST', 'GetMap')
        if type_ == 'GetCapabilities':
            self.serialize = self._get_capabilities(environ)
            self.headers.append( ('Content-type', 'text/xml') )
            self.headers.append( ('Access-Control-Allow-Origin', '*') )
        elif type_ == 'GetMap':
            self.serialize = self._get_map(environ)
            self.headers.append( ('Content-type', 'image/png') )
        elif type_ == 'GetColorbar':
            self.serialize = self._get_colorbar(environ)
            self.headers.append( ('Content-type', 'image/png') )
        else:
            raise HTTPBadRequest('Invalid REQUEST "%s"' % type_)

        return BaseResponse.__call__(self, environ, start_response)
Exemplo n.º 16
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-type', 'text/html; charset=utf-8'),
     ])
Exemplo n.º 17
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.append( ('Content-description', 'dods_wms') )
Exemplo n.º 18
0
 def setUp(self):
     """Instantiate a response."""
     self.response = BaseResponse(VerySimpleSequence)
Exemplo n.º 19
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([("Content-description", "dods_xls"), ("Content-type", "application/vnd.ms-excel")])
Exemplo n.º 20
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.append(('Content-description', 'dods_wms'))
Exemplo n.º 21
0
 def __init__(self, dataset, request=None):
     BaseResponse.__init__(self, dataset, request)
Exemplo n.º 22
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([("Content-description", "dods_dds"), ("Content-type", "text/plain; charset=utf-8")])
Exemplo n.º 23
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([("Content-description", "dods_form"), ("Content-type", "text/html")])
Exemplo n.º 24
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_xls'),
         ('Content-type', 'application/vnd.ms-excel'),
     ])
Exemplo n.º 25
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_netcdf'),
             ('Content-type', 'application/x-netcdf'),
             ])
Exemplo n.º 26
0
 def __init__(self, dataset=None):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_help'),
         ('Content-type', 'text/html'),
     ])
Exemplo n.º 27
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_xlsx'),
             ('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
             ])
Exemplo n.º 28
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)

        self.nc = netcdf_file(None)
        if 'NC_GLOBAL' in self.dataset.attributes:
            self.nc._attributes.update(self.dataset.attributes['NC_GLOBAL'])

        dimensions = [var.dimensions for var in walk(self.dataset) if isinstance(var, BaseType)]
        dimensions = set(reduce(lambda x, y: x+y, dimensions))
        try:
            unlim_dim = self.dataset.attributes['DODS_EXTRA']['Unlimited_Dimension']
        except:
            unlim_dim = None

        # GridType
        for grid in walk(dataset, GridType):

            # add dimensions
            for dim, map_ in grid.maps.items():
                if dim in self.nc.dimensions:
                    continue

                n = None if dim == unlim_dim else grid[dim].data.shape[0]
                self.nc.createDimension(dim, n)
                if not n:
                    self.nc.set_numrecs(grid[dim].data.shape[0])
                var = grid[dim]

                # and add dimension variable
                self.nc.createVariable(dim, var.dtype.char, (dim,), attributes=var.attributes)

            # finally add the grid variable itself
            base_var = grid[grid.name]
            var = self.nc.createVariable(base_var.name, base_var.dtype.char, base_var.dimensions, attributes=base_var.attributes)

        # Sequence types!
        for seq in walk(dataset, SequenceType):

            self.nc.createDimension(seq.name, None)
            try:
                n = len(seq)
            except TypeError:
                # FIXME: materializing and iterating through a sequence to find the length
                # could have performance problems and could potentially consume the iterable
                # Do lots of testing here and determine the result of not calling set_numrecs()
                n = len( [ x for x in seq[seq.keys()[0]] ])
            self.nc.set_numrecs(n)

            dim = seq.name,

            for child in seq.children():
                dtype = child.dtype
                # netcdf does not have a date type, so remap to float
                if dtype == np.dtype('datetime64'):
                    dtype = np.dtype('float32')
                elif dtype == np.dtype('object'):
                    raise TypeError("Don't know how to handle numpy type {0}".format(dtype))
                        
                var = self.nc.createVariable(child.name, dtype.char, dim, attributes=child.attributes)

        self.headers.extend([
            ('Content-type', 'application/x-netcdf')
        ])
        # Optionally set the filesize header if possible
        try:
            self.headers.extend([('Content-length', self.nc.filesize)])
        except ValueError:
            pass
Exemplo n.º 29
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.append(('Content-type', 'application/json'))
Exemplo n.º 30
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-type', 'text/html; charset=utf-8'),
     ])
Exemplo n.º 31
0
 def __init__(self, dataset=None):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_version'),
             ('Content-type', 'text/plain'),
             ])
Exemplo n.º 32
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_ascii'),
         ('Content-type', 'text/plain'),
     ])
Exemplo n.º 33
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_dds'),
             ('Content-type', 'text/plain; charset=utf-8'),
             ])
Exemplo n.º 34
0
    def __init__(self, dataset):
        BaseResponse.__init__(self, dataset)

        self.nc = netcdf_file(None)
        if 'NC_GLOBAL' in self.dataset.attributes:
            self.nc._attributes.update(self.dataset.attributes['NC_GLOBAL'])

        dimensions = [
            var.dimensions for var in walk(self.dataset)
            if isinstance(var, BaseType)
        ]
        dimensions = set(reduce(lambda x, y: x + y, dimensions))
        try:
            unlim_dim = self.dataset.attributes['DODS_EXTRA'][
                'Unlimited_Dimension']
        except:
            unlim_dim = None

        # GridType
        for grid in walk(dataset, GridType):

            # add dimensions
            for dim, map_ in grid.maps.items():
                if dim in self.nc.dimensions:
                    continue

                n = None if dim == unlim_dim else grid[dim].data.shape[0]
                self.nc.createDimension(dim, n)
                if not n:
                    self.nc.set_numrecs(grid[dim].data.shape[0])
                var = grid[dim]

                # and add dimension variable
                self.nc.createVariable(dim,
                                       var.dtype.char, (dim, ),
                                       attributes=var.attributes)

            # finally add the grid variable itself
            base_var = grid[grid.name]
            var = self.nc.createVariable(base_var.name,
                                         base_var.dtype.char,
                                         base_var.dimensions,
                                         attributes=base_var.attributes)

        # Sequence types!
        for seq in walk(dataset, SequenceType):

            self.nc.createDimension(seq.name, None)
            try:
                n = len(seq)
            except TypeError:
                # FIXME: materializing and iterating through a sequence to find the length
                # could have performance problems and could potentially consume the iterable
                # Do lots of testing here and determine the result of not calling set_numrecs()
                n = len([x for x in seq[seq.keys()[0]]])
            self.nc.set_numrecs(n)

            dim = seq.name,

            for child in seq.children():
                dtype = child.dtype
                # netcdf does not have a date type, so remap to float
                if dtype == np.dtype('datetime64'):
                    dtype = np.dtype('float32')
                elif dtype == np.dtype('object'):
                    raise TypeError(
                        "Don't know how to handle numpy type {0}".format(
                            dtype))

                var = self.nc.createVariable(child.name,
                                             dtype.char,
                                             dim,
                                             attributes=child.attributes)

        self.headers.extend([('Content-type', 'application/x-netcdf')])
        # Optionally set the filesize header if possible
        try:
            self.headers.extend([('Content-length', self.nc.filesize)])
        except ValueError:
            pass