source: TI05-delivery/ows_framework/trunk/ows_server/ows_server/lib/base.py @ 2802

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/trunk/ows_server/ows_server/lib/base.py@2802
Revision 2802, 5.6 KB checked in by lawrence, 13 years ago (diff)

Adding more functionality to the selections ...

Line 
1from pylons import Response, c, g, cache, request, session
2from pylons.controllers import WSGIController
3from pylons.decorators import jsonify, validate
4from pylons.templating import render, render_response
5from pylons.helpers import abort, redirect_to, etag_cache
6from pylons.i18n import N_, _, ungettext
7from paste.request import construct_url
8import ows_server.models as model
9import ows_server.lib.helpers as h
10from ows_server.lib.security_util import setSecuritySession, LoginServiceQuery
11from ows_common import exceptions as OWS_E
12from ows_common.operations_metadata import OperationsMetadata, Operation, RequestMethod
13from ows_common.get_capabilities import ServiceMetadata
14import ows_common.xml
15
16
17try:
18    from xml.etree import ElementTree as ET
19except ImportError:
20    from elementtree import ElementTree as ET
21
22import logging
23logger = logging.getLogger('ows_server.lib.base')
24
25class BaseController(WSGIController):
26   
27    def __call__(self, environ, start_response):
28        # Insert any code to be run per request here. The Routes match
29        # is under environ['pylons.routes_dict'] should you want to check
30        # the action or route vars here
31        c.requestURL=construct_url(environ)
32        if 'h' in request.params:
33            setSecuritySession()
34           
35            if 'panelView' not in session:
36                session['panelView']='History'
37            session.save()
38           
39            # TODO Make the redirect tidier ...
40            qs = LoginServiceQuery.stripFromURI()
41
42            cc=construct_url(environ,querystring=qs)
43            h.redirect_to(cc)
44       
45        #organise the information needed by pagetabs ...
46        # TODO avoid this for the server controllers ...
47       
48        c.pageTabs=[('Search',g.discoveryURL)]
49        if 'results' in session: c.pageTabs.append(('Results',session['results']))
50        if 'lastViewed' in session: c.pageTabs.append(('Display',session['lastViewed']))
51       
52        if 'ndgSec' in session:
53            c.pageTabs.append(('Selections',h.url_for(controller='selection',action='index')))
54            c.pageTabs.append(('Visualise','Blah'))
55            c.pageTabs.append(('Download','Blah'))
56
57        return WSGIController.__call__(self, environ, start_response)
58   
59class OwsController(BaseController):
60    def __call__(self, environ, start_response):
61
62        # All OWS parameter names are case insensitive.
63        req = request._current_obj()
64        self.ows_params = {}
65        for k in req.params:
66            self.ows_params[k.lower()] = req.params[k]       
67
68        try:
69            self._fixOwsAction(environ)
70            return super(OwsController, self).__call__(environ, start_response)
71        except OWS_E.OwsError, e:
72            logger.exception(e)
73            return render_response('exception_report', report=e.report,
74                                   format='xml')
75           
76 
77    def _fixOwsAction(self, environ):
78        # Override the Routes action from the request query parameter
79        try:
80            action = self.ows_params['request']
81        except KeyError:
82            raise OWS_E.MissingParameterValue('REQUEST parameter not specified', 'REQUEST')
83
84        # Check action is a method in self
85        if not getattr(self, action):
86            raise OWS_E.InvalidParameterValue('request=%s not supported' % action, 'REQUEST')
87
88        # override routes action with request
89        environ['pylons.routes_dict']['action'] = action
90        del self.ows_params['request']
91
92    def _loadCapabilities(self):
93        """
94        creates an ows_common.get_capabilities.ServiceMetadata object
95        by consulting the paste configuration and annotations in the
96        controller definition.
97
98        """
99        # Deduce ows_endpoint from routes
100        ows_endpoint = h.url_for(controller=request.environ['pylons.routes_dict']['controller'])
101       
102        # Get the server-level configuration data from an XML file
103        config = request.environ['paste.config']
104        sm_tree = ET.parse(config['ows_common_config'])
105        sm = ows_common.xml.service_metadata(sm_tree.getroot())
106       
107        # Extract service-level parameters and constraint
108        parameters = getattr(self, '_ows_parameters', {})
109        constraints = getattr(self, '_ows_constraints', {})
110        versions = getattr(self, '_ows_versions', [])
111       
112        # Extract operation-level parameters and constraints
113        od = {}
114        for attr in dir(self):
115            op = getattr(self, attr)
116            if hasattr(op, '_ows_name'):
117                p = getattr(op, '_ows_parameters', {})
118                c = getattr(op, '_ows_constraints', {})
119                od[op._ows_name] = Operation(get=RequestMethod(href=ows_endpoint),
120                                             post=None,
121                                             parameters=p,
122                                             constraints=c,
123                                             name=op._ows_name)
124       
125        sm.operationsMetadata = OperationsMetadata(od, constraints, parameters)
126        sm.serviceIdentification.serviceTypeVersions = versions
127        return sm
128
129    def _renderCapabilities(self, template='ows/get_capabilities'):
130        """
131        The standard way of returning a Capabilities document.
132
133        Each subclass should implement self._load_capabilities() and call
134        this method to return a response object.
135
136        """
137        c.service_metadata = self._loadCapabilities()       
138        r = render_response(template, format='xml')
139        r.headers['content-type'] = 'text/xml'
140        return r
141
142
143# Include the '_' function in the public names
144__all__ = [__name for __name in locals().keys() if not __name.startswith('_') \
145           or __name == '_']
Note: See TracBrowser for help on using the repository browser.