source: TI05-delivery/ows_framework/trunk/ows_server/ows_server/lib/csml_util.py @ 2603

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/trunk/ows_server/ows_server/lib/csml_util.py@2603
Revision 2603, 4.0 KB checked in by domlowe, 14 years ago (diff)

adding option to publish netcdf file in public directory, off by default

Line 
1# Copyright (C) 2007 STFC & NERC (Science and Technology Facilities Council).
2# This software may be distributed under the terms of the
3# Q Public License, version 1.0 or later.
4# http://ndg.nerc.ac.uk/public_docs/QPublic_license.txt
5"""
6csml access routines.
7
8@author: Stephen Pascoe
9"""
10from pylons import Response, c, g, cache, request, session
11
12import csml, cdms
13import os
14import zipfile
15import tempfile
16
17def get_csml_doc(file):
18    """
19    A trivial document retrieval function.
20
21    This could be replaced with a proper csml server object that supports
22    multiple stores (filesystem, exist) and cache's the results for
23    performance.
24
25    """
26    csml_dir = request.environ['paste.config']['app_conf']['csml_dir']
27    path = os.path.join(csml_dir, file)
28    if os.path.exists(path+'.csml'):
29        f = path+'.csml'
30    elif os.path.exists(path+'.xml'):
31        f = path +'.xml'
32    else:
33        raise ValueError("Cannot find CSML file %s" % file)
34   
35    d = csml.parser.Dataset()
36    d.parse(f)
37       
38    return d
39
40       
41def extractToNetCDF(feature, sel, publish=False):
42    """
43       performs the CSML subset and returns a filename of the netcdf extract
44       publish flag is used to indicate that the netcdf file should be made available to the webserver (for asynchronous delivery)
45    """
46    # Get temporary extract dir
47    extract_dir = request.environ['paste.config']['app_conf']['tmp_dir']
48   
49    # Subset the feature
50    (fd, filename) = tempfile.mkstemp('.nc', 'csml_wms_', extract_dir); os.close(fd)
51    feature.subsetToGridSeries(ncname=os.path.basename(filename),
52                               outputdir=os.path.dirname(filename) ,**sel)
53   
54    #if publishing to download directory is required, do so and return publishable file name
55    #used e.g. in WCS when "STORE = true"
56    if publish !=False:
57        publish_dir=request.environ['paste.config']['app_conf']['publish_dir']
58        #copy file from tmp_dir to publish directory
59        publishedName=publish_dir +'/'+os.path.basename(filename)
60        os.system ("cp %s %s" % (filename, publishedName))
61        return publishedName
62    return filename
63       
64def extractToVariable(feature, sel):
65    """
66      calls extractToNetCDF to get the netcdf file, then returns a cdms variable from this file
67    """
68    #call extractToNetCDF:
69    filename = extractToNetCDF(feature, sel)
70    d = cdms.open(filename)
71    var = d(feature.name.CONTENT, squeeze=1)
72    # Work around for CSML bug
73    #var = d(feature.name.CONTENT, longitude=sel['longitude'], latitude=sel['latitude'],
74    #        squeeze=1)
75
76    d.close()
77    #os.remove(filename)
78    return var
79       
80class CsmlBundle(csml.API.csmlContainer.Container):
81    """
82    A quick stab at bundling CSML.
83
84    """
85    def __init__(self, context, **kwargs):
86        """
87        @param context: A directory path to store the CSML and NetCDF
88        """
89        self.context = context
90        kwargs['csmlpath'] = os.path.join(context, 'container.xml')
91        super(CsmlBundle, self).__init__(**kwargs)
92
93    def add(self, fpd):
94        """
95        Overrides the file storage descriptor so that the CSML points relative to the
96        bundle context
97
98        @warning: THIS IS A HACK!
99
100        """
101        (feature, path, desc) = fpd
102        if os.path.dirname(path) != self.context:
103            raise ValueError, "Extract not in bundle context"
104        desc.fileName.CONTENT = os.path.basename(path)
105
106        return super(CsmlBundle, self).add(fpd)
107
108    def join(self, *p):
109        return os.path.join(self.context, *p)
110
111    def makeBundle(self, file, bundleName=None):
112        """
113        Writes the bundle to a zipfile.
114
115        @param file: path or file-like object (see zipfile docs)
116
117        """
118        if bundleName is None:
119            bundleName = os.path.splitext(os.path.basename(file))[0]
120       
121        zf = zipfile.ZipFile(file, 'w')
122        self.getContents()
123        for f in self.containerContents:
124            zf.write(f, os.path.join(bundleName, os.path.basename(f)))
125        zf.close()
126
127        return file
Note: See TracBrowser for help on using the repository browser.