source: TI05-delivery/ows_framework/branches/ows_framework-refactor/ows_server/ows_server/lib/ows_controller.py @ 3184

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/branches/ows_framework-refactor/ows_server/ows_server/lib/ows_controller.py@3184
Revision 3184, 4.7 KB checked in by spascoe, 12 years ago (diff)

Things missed in previous commit

Line 
1"""
2Base controller for OGC Web Services (OWS).
3
4@author: Stephen Pascoe
5"""
6
7
8from pylons import Response, c, g, cache, request, session
9from pylons.controllers import WSGIController
10from pylons.decorators import jsonify, validate
11from pylons.templating import render, render_response
12from pylons.helpers import abort, redirect_to, etag_cache
13
14import ows_server.models as model
15import ows_server.lib.helpers as h
16from ows_server.lib.security_util import setSecuritySession, LoginServiceQuery
17from ows_common import exceptions as OWS_E
18from ows_common.operations_metadata import OperationsMetadata, Operation, RequestMethod
19from ows_common.get_capabilities import ServiceMetadata
20import ows_common.xml
21
22
23try:
24    from xml.etree import ElementTree as ET
25except ImportError:
26    from elementtree import ElementTree as ET
27
28import logging
29logger = logging.getLogger(__name__)
30
31# Configure
32EXCEPTION_TYPE = request.environ['ndgConfig'].get('OWS_SERVER', 'exception_type', 'ogc').lower()
33
34
35
36class OwsController(WSGIController):
37    def __call__(self, environ, start_response):
38
39        # All OWS parameter names are case insensitive.
40        req = request._current_obj()
41        self.ows_params = {}
42        for k in req.params:
43            self.ows_params[k.lower()] = req.params[k]       
44
45        # If the EXCEPTION_TYPE is 'pylons' let Pylons catch any exceptions.
46        # Otherwise send an OGC exception report for any OWS_E.OwsError
47        if 'pylons' in EXCEPTION_TYPE:
48            self._fixOwsAction(environ)
49            return super(OwsController, self).__call__(environ, start_response)
50        else:
51            try:
52                self._fixOwsAction(environ)
53                return super(OwsController, self).__call__(environ, start_response)
54            except OWS_E.OwsError, e:
55                logger.exception(e)
56
57                r=render_response('exception_report', report=e.report, format='xml')
58                r.headers['content-type'] = 'text/xml'
59                return r
60
61
62    def _fixOwsAction(self, environ):
63        # Override the Routes action from the request query parameter
64        try:
65            action = self.ows_params['request']
66        except KeyError:
67            raise OWS_E.MissingParameterValue('REQUEST parameter not specified', 'REQUEST')
68
69        # Check action is a method in self
70        if not getattr(self, action):
71            raise OWS_E.InvalidParameterValue('request=%s not supported' % action, 'REQUEST')
72
73        # override routes action with request
74        environ['pylons.routes_dict']['action'] = action
75        del self.ows_params['request']
76
77    def _loadCapabilities(self):
78        """
79        creates an ows_common.get_capabilities.ServiceMetadata object
80        by consulting the paste configuration and annotations in the
81        controller definition.
82
83        """
84        # Deduce ows_endpoint from routes
85        ows_endpoint = h.url_for(controller=request.environ['pylons.routes_dict']['controller'])
86       
87        #Deduce base_url from config
88        base_url =request.environ['ndgConfig'].get('DEFAULT','server')
89
90       
91        # Get the server-level configuration data from an XML file
92        config = request.environ['paste.config']
93        sm_tree = ET.parse(config['ows_common_config'])
94        sm = ows_common.xml.service_metadata(sm_tree.getroot())
95       
96        # Extract service-level parameters and constraint
97        parameters = getattr(self, '_ows_parameters', {})
98        constraints = getattr(self, '_ows_constraints', {})
99        versions = getattr(self, '_ows_versions', [])
100       
101        # Extract operation-level parameters and constraints
102        od = {}
103        for attr in dir(self):
104            op = getattr(self, attr)
105            if hasattr(op, '_ows_name'):
106                p = getattr(op, '_ows_parameters', {})
107                c = getattr(op, '_ows_constraints', {})
108                od[op._ows_name] = Operation(get=RequestMethod(href=base_url+ows_endpoint),
109                                             post=None,
110                                             parameters=p,
111                                             constraints=c,
112                                             name=op._ows_name)
113       
114        sm.operationsMetadata = OperationsMetadata(od, constraints, parameters)
115        sm.serviceIdentification.serviceTypeVersions = versions
116        return sm
117
118    def _renderCapabilities(self, template='ows/get_capabilities'):
119        """
120        The standard way of returning a Capabilities document.
121
122        Each subclass should implement self._load_capabilities() and call
123        this method to return a response object.
124
125        """
126        c.service_metadata = self._loadCapabilities()       
127        r = render_response(template, format='xml')
128        r.headers['content-type'] = 'text/xml'
129        return r
130
Note: See TracBrowser for help on using the repository browser.