예제 #1
0
파일: __init__.py 프로젝트: pydap/pydap
    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'),
     ])
예제 #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)))
예제 #4
0
파일: dods.py 프로젝트: phrrngtn/pydap
    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"),
        ]
예제 #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'),
        ])
예제 #8
0
파일: __init__.py 프로젝트: taeold/pydap
    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"),
        ]
예제 #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))
예제 #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)
예제 #11
0
파일: help.py 프로젝트: OPENDAP/pydap
 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)
예제 #12
0
파일: html.py 프로젝트: hyoklee/pydap
    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)
예제 #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)
예제 #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)
예제 #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)
예제 #16
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-type', 'text/html; charset=utf-8'),
     ])
예제 #17
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.append( ('Content-description', 'dods_wms') )
예제 #18
0
 def setUp(self):
     """Instantiate a response."""
     self.response = BaseResponse(VerySimpleSequence)
예제 #19
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([("Content-description", "dods_xls"), ("Content-type", "application/vnd.ms-excel")])
예제 #20
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.append(('Content-description', 'dods_wms'))
예제 #21
0
 def __init__(self, dataset, request=None):
     BaseResponse.__init__(self, dataset, request)
예제 #22
0
파일: dds.py 프로젝트: bolkhovsky/pydap
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([("Content-description", "dods_dds"), ("Content-type", "text/plain; charset=utf-8")])
예제 #23
0
파일: html.py 프로젝트: hyoklee/pydap
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([("Content-description", "dods_form"), ("Content-type", "text/html")])
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_xls'),
         ('Content-type', 'application/vnd.ms-excel'),
     ])
예제 #25
0
파일: __init__.py 프로젝트: NERSC/pydap
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_netcdf'),
             ('Content-type', 'application/x-netcdf'),
             ])
예제 #26
0
 def __init__(self, dataset=None):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_help'),
         ('Content-type', 'text/html'),
     ])
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_xlsx'),
             ('Content-type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
             ])
예제 #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
예제 #29
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.append(('Content-type', 'application/json'))
예제 #30
0
파일: info.py 프로젝트: lukecampbell/pydap
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-type', 'text/html; charset=utf-8'),
     ])
예제 #31
0
파일: version.py 프로젝트: OPENDAP/pydap
 def __init__(self, dataset=None):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_version'),
             ('Content-type', 'text/plain'),
             ])
예제 #32
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
         ('Content-description', 'dods_ascii'),
         ('Content-type', 'text/plain'),
     ])
예제 #33
0
 def __init__(self, dataset):
     BaseResponse.__init__(self, dataset)
     self.headers.extend([
             ('Content-description', 'dods_dds'),
             ('Content-type', 'text/plain; charset=utf-8'),
             ])
예제 #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