Changeset 3707


Ignore:
Timestamp:
31/03/08 17:57:21 (11 years ago)
Author:
mkochan
Message:

Changed HTML generation in csmlGrapher -- not using ElementTree now.

Location:
DPPP/kml/csml2kml/python/csml2kmlpylon/csml2kmlpylon/controllers
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • DPPP/kml/csml2kml/python/csml2kmlpylon/csml2kmlpylon/controllers/csmlGrapher.py

    r3705 r3707  
    7070        return BaseController.__call__(self, environ, start_response) 
    7171 
     72    def _datetimeTo1Jan1970(self, datetime): 
     73        ''' 
     74        Convert datetime to format a'la C{1-JAN-1970}. 
     75        @param datetime: The datetime to be converted. 
     76        @type datetime: C{matplotlib.dates.datetime.datetime} 
     77        @return: A string like "1-JAN-1970" or "31-MAR-2008". 
     78        @rtype: C{str} 
     79        ''' 
     80        # Use format e.g. "1-JAN-1970" or "31-MAR-2008". 
     81        monthCodes = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] 
     82        return repr(datetime.day) + '-' + monthCodes[datetime.month-1] + '-' + repr(datetime.year) 
     83 
    7284    def _datetimeToGeoServerDate(self, datetime, datetimeQueryFormat): 
     85        ''' 
     86        Convert datetime to one of the string datetime formats used in URL queries to WFS. 
     87        @param datetime: The datetime to be converted. 
     88        @type datetime: C{matplotlib.dates.datetime.datetime} 
     89        @param datetimeQueryFormat: Either C{UTC_TIMESTAMP} or C{1-JAN-1970}. 
     90        @type datetimeQueryFormat: C{str} 
     91        @return: If datetimeQueryFormat is C{UTC_TIMESTAMP}, returns a UTC timestamp; 
     92        if datetimeQueryFormat is C{1-JAN-1970}, returns a string like "1-JAN-1970" or "31-MAR-2008". 
     93        @rtype: C{str} 
     94        ''' 
    7395        if datetimeQueryFormat == 'UTC_TIMESTAMP': 
    7496            # Use the UTC timestamp format, generate timestamp. 
     
    7799            return '%04d-%02d-%02dT%02d:%02d:%02d' % (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second) 
    78100        elif datetimeQueryFormat == '1-JAN-1970': 
    79             # Use format e.g. "1-JAN-1970" or "31-MAR-2008". 
    80             monthCodes = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'] 
    81             return repr(datetime.day) + '-' + monthCodes[datetime.month-1] + '-' + repr(datetime.year) 
     101            return self._datetimeTo1Jan1970(datetime) 
    82102        else: 
    83103            raise ValueError('Wrong keyword in the <DatetimeQueryFormat> tag in the config file.') 
     
    85105    def _retrieveCsmlPointSeriesFeature(self, dataset, station_name, feature_id): 
    86106        ''' 
    87         @return: A C{PointSeriesFeature} object representing the single CSML feature if the feature was found; 
     107        Retrieve CSML from WFS using an URL query. 
     108        @param dataset: The dataset used to retrieve from 
     109        @type: C{Dataset} 
     110        @param station_name: Unique full name of the station, eg C{FAIR ISLE}. 
     111        @type station_name: C{str} 
     112        @param feature_id: Unique id of the CSML feature, eg C{air_temperature}. 
     113        @type feature_id: C{str} 
     114        @return: A C{csml.PointSeriesFeature} object representing the single CSML feature if the feature was found; 
    88115        C{None} if a feature collection has been returned, but contains no CSML features (this happens when 
    89116        there are no measured time points in the used time interval). 
    90117        @throws: A C{LookupError} exception with a message if there is no response from the server. 
    91118        ''' 
    92        
    93119        # Prepare the request for the dataset's GeoServer 
    94120        geoServerRequestUrl = urllib.quote(dataset.geoServerUrl + '?request=getfeature&service=wfs&version=1.1.0&typename=csml:PointSeriesFeature&filter=<ogc:Filter xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml"><ogc:And><ogc:PropertyIsEqualTo><ogc:PropertyName>gml:description</ogc:PropertyName><ogc:Literal>'+ station_name +'</ogc:Literal></ogc:PropertyIsEqualTo><ogc:PropertyIsEqualTo><ogc:PropertyName>csml:parameter/swe:Phenomenon/gml:name</ogc:PropertyName><ogc:Literal>'+ feature_id +'</ogc:Literal></ogc:PropertyIsEqualTo><ogc:PropertyIsBetween><ogc:PropertyName>csml:value/csml:PointSeriesCoverage/csml:pointSeriesDomain/csml:TimeSeries/csml:timePositionList</ogc:PropertyName><ogc:LowerBoundary><ogc:Literal>'+ self._datetimeToGeoServerDate(self.displayIntervalStart, dataset.datetimeQueryFormat) +'</ogc:Literal></ogc:LowerBoundary><ogc:UpperBoundary><ogc:Literal>'+ self._datetimeToGeoServerDate(self.displayIntervalEnd, dataset.datetimeQueryFormat) +'</ogc:Literal></ogc:UpperBoundary></ogc:PropertyIsBetween></ogc:And></ogc:Filter>', '/._:?&=') 
     
    125151        Handler for plotting a specific PointSeries feature given by URL parameter "feature_id". 
    126152        Retrieves the data from a web service, which should preferably run on the same machine.  
    127  
    128         Request parameters: 
    129                                dataset_id      Unique identifier of the dataset to use. 
    130                                feature_id      Unique identifier of the requested CSML PointSeries feature. 
    131                                station_name    Name of the requested station. 
     153        Request URL parameters are: 
     154        dataset_id      Unique identifier of the dataset to use. 
     155        feature_id      Unique identifier of the requested CSML PointSeries feature. 
     156        station_name    Name of the requested station. 
    132157                                
    133158        Response:              An image/png of the time series for the CSML PointSeries feature. 
     
    135160        def _plot_feature(feature, dataset): 
    136161            ''' 
    137             Plot a PointSeries feature using matplotlib, into a temporary file 
     162            Plot a PointSeries feature using matplotlib, into a temporary file. 
     163            @return: An file-like object which represents the file, which can be read from and also closed 
     164            as a normal file. 
     165            @rtype: C{tempfile.NamedTemporaryFile} 
    138166            ''' 
    139167             
     
    192220 
    193221            # Generate tick locator and formatter; these determine the time axis: locator determines tick positions 
    194             # and formatter format of time 
     222            # and formatter format of time. There will be a total of eight ticks. 
    195223            print '---start_date:' + str(start_date) 
    196224            print '---end_date:' + str(end_date) 
     
    205233                uom = uom.upper() 
    206234 
    207             # Prepare the plot the figure (actual plotting actions are postponed until save) 
     235            # Prepare the plot of the figure (matplotlib does the actual plotting actions are postponed on file save) 
    208236            fig = figure() 
    209237            plot_date(elapsed_times, vals, 'b-', xdate=True, lw=1) 
    210238            plot_date(elapsed_times, vals, 'go', markeredgecolor = 'g', xdate=True, lw=2) 
    211239            ax = gca() 
    212             ax.xaxis.set_major_locator(tickLocator) 
     240            ax.xaxis.set_major_locator(tickLocator)        
    213241            ax.xaxis.set_major_formatter(tickFormatter) 
    214             fig.autofmt_xdate()  # show times without overlaps 
     242            fig.autofmt_xdate()  # make sure times are shown with no overlapping timestamps 
    215243            time_format = '%d-%b-%Y %H:%M:%S UTC' 
    216244            xlabel('Times between %s and %s ' % (start_date.strftime(time_format), end_date.strftime(time_format))) 
     
    227255        def _set_response(tempFile): 
    228256            ''' 
    229             Set the WSGI response to an image, containing image read from a temporary location. 
     257            Set the service's response to an image, containing image read from a temporary location. 
     258            @param tempFile: An object representing a temporary file 
     259            @type tempFile: C{tempfile.NamedTemporaryFile} 
    230260            ''' 
    231261            img = Image.open(tempFile.name) 
     
    235265            response.content = buf.getvalue() 
    236266             
    237         #---------------------- 
     267        #---------------------- (function main body) ----------------------- 
    238268 
    239269        # Get parameters from the request object 
     
    314344        # Generate HTML with a list of CSML features contained in the station. 
    315345        # Currently, this is done simply by directly generating HTML (i.e. no template was used). 
    316         htmlElement = Element('html') 
    317         SubElement(htmlElement, 'title').text = 'List of CSML features for station ' + station_name 
    318         bodyElement = SubElement(htmlElement, 'body') 
    319         SubElement(bodyElement, 'h2').text = 'List of CSML features for station ' + station_name 
    320         tableElement = SubElement(bodyElement, 'table') 
    321         tableElement.set('border', '1') 
    322         headingRowElement = SubElement(tableElement, 'tr') 
    323         SubElement(headingRowElement, 'th').text = 'Feature name' 
    324         SubElement(headingRowElement, 'th').text = 'Data collected since' 
    325         SubElement(headingRowElement, 'th').text = 'Data collected until ' 
     346        htmlRows = '' 
    326347        for stationFeature in wfsStation.stationFeatures: 
    327348            if self.displayIntervalStart >= stationFeature.collectBeginDate and self.displayIntervalEnd <= stationFeature.collectEndDate: 
    328                 rowElement = SubElement(tableElement, 'tr') 
    329                 featureNameElement = SubElement(rowElement, 'td') 
    330                 anchorElement = SubElement(featureNameElement, 'a') 
    331                 linkToGrapher = self.servedFromUrl + '/plot?dataset_id=' + dataset_id + '&station_name=' + station_name + '&feature_id=' + stationFeature.featureId 
    332                 anchorElement.set('href', linkToGrapher) 
    333                 anchorElement.text = stationFeature.featureId 
    334                 SubElement(rowElement, 'td').text = self._datetimeToGeoServerDate(stationFeature.collectBeginDate) 
    335                 SubElement(rowElement, 'td').text = self._datetimeToGeoServerDate(stationFeature.collectEndDate) 
    336  
    337         htmlStringIO = StringIO() 
    338         ElementTree(htmlElement).write(htmlStringIO) 
    339  
     349                htmlLinkToGrapher = '%s/plot?dataset_id=%s&station_name=%s&feature_id=%s' % ( 
     350                    self.servedFromUrl, dataset_id, station_name, stationFeature.featureId 
     351                    ) 
     352                htmlRow = '<tr><td>%s</td><td>%s</td><td>%s</td></tr>' % ( 
     353                    '<a href="%s">%s</a>' % (htmlLinkToGrapher, stationFeature.featureId), 
     354                    self._datetimeTo1Jan1970(stationFeature.collectBeginDate), 
     355                    self._datetimeTo1Jan1970(stationFeature.collectEndDate) 
     356                    ) 
     357                htmlRows = htmlRows + htmlRow 
     358        htmlTable = '<table border="1"><tr><th>Feature name</th><th>Data collected since</th><th>Data collected until</th></tr>%s</table>' % htmlRows 
     359        htmlHeading = 'List of CSML features for station ' + station_name 
     360        htmlUsage = '' 
     361        htmlBody = '<h2>%s</h2>%s<p>%s' % (htmlHeading, htmlUsage, htmlTable) 
     362        htmlTitle = htmlHeading 
     363        html = '<html><title>%s</title><body>%s</body></html>' % (htmlTitle, htmlBody) 
     364 
     365        print html 
    340366        response.content_type = 'text/html' 
    341         response.content = htmlStringIO.getvalue() 
     367        response.content = html 
Note: See TracChangeset for help on using the changeset viewer.