source: TI05-delivery/ows_framework/trunk/ows_server/ows_server/controllers/retrieve.py @ 3536

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI05-delivery/ows_framework/trunk/ows_server/ows_server/controllers/retrieve.py@3536
Revision 3536, 7.1 KB checked in by cbyrom, 12 years ago (diff)

Upgrade the server code to make consistent with newer pylons codebase - v0.9.6.1.
This mainly involves the replacement of the Response object, and associated methods,
with the inbuild, default response object. Typical changes include:

render_response -> render - with required settings on the response object
made before the render call against the response object

Response(...) -> response.write() - for content + response.headers.. = .. for headers info

  • also included the replacement of depricated functions, as highlighted by

the server logging

Line 
1
2from ows_server.lib.base import *
3from ows_server.models import Utilities
4from ndgUtils import ndgObject
5from paste.request import parse_querystring
6from ows_server.models import stubB,DIF
7from ows_server.lib import mailer
8from ows_server.lib.ndgInterface import interface
9from xml.parsers.expat import ExpatError
10
11class RetrieveController(BaseController):
12    ''' Provides the pylons controller for retrieving NDG documents. The simple model
13    is now that an attempt to retrieve/uri will parse the uri, read the config file,
14    and if the local server name is not the same as the uri server name. '''
15   
16    def __setup(self,uri):
17        ''' Common setup stuff for all the actions on this controller '''
18        try:
19            self.uri=ndgObject(uri)
20        except ValueError,e:
21            return e
22        self.cf=request.environ['ndgConfig']
23        self.uri.setConfig(self.cf)
24        self.requestor=request.environ['REMOTE_ADDR']
25        self.logger=0
26        if logger: self.logger=logger
27        self.inputs=dict(parse_querystring(request.environ))
28
29
30        # NB: we could have two types of query string argument:
31        #   format= (raw,html) and
32        #   outputSchema=(original, someSchema)
33        self.format=''
34        if 'format' in self.inputs: self.format=self.inputs['format']
35        self.outputSchema=''
36        if 'outputSchema' in self.inputs: self.outputSchema=self.inputs['outputSchema']
37
38        # Add selected granules to context
39        #c.selectedGranules = [g_uri for g_uri, g_name in session.get('selection', [])]
40                             
41
42        return 0
43       
44    def index(self,uri):
45        ''' Returns the document unadorned in anyway, i.e. the raw xml'''
46        status=self.__setup(uri)
47        if status:
48            c.xml='<p>%s</p>'%status
49            response.status_code = 400
50            return render('error')
51       
52        status,x=interface.GetXML(uri,outputSchema=self.outputSchema)
53        if status:
54            #(the return object x is an xmlHandler object)
55            c.xml=x.xmls
56            response.headers['Content-Type'] = 'application/xml'
57            response.write(c.xml)
58        else:
59            e=404
60            if x.startswith('<p> Access'): e=401
61            response.status_code = e
62            return render('error')
63       
64    def view(self,uri):
65        ''' Returns either an html marked up version of the xml, or a properly laid
66        out version of the document '''
67        c.doc=None
68        status=self.__setup(uri)
69        if status:
70            c.xml='<p>%s</p>'%status
71            response.status_code = 400
72            return render('error')
73
74        status,x=interface.GetXML(uri,outputSchema=self.outputSchema)
75        c.title='Viewing [%s]'%self.uri
76       
77        if status:
78            #(the return object x is an xmlHandler object)
79            viewFormat=self.uri.schema
80            if self.outputSchema!='': viewFormat=self.outputSchema
81            if self.format not in ('xml','raw'):
82                if viewFormat=='NDG-B1':
83                    r='stubB'
84                    c.doc=stubB.stubB(x.tree,self.cf)
85                    c.tbinfo=self.__mytb(c.doc.name)
86                    name=c.doc.abbreviation
87                elif viewFormat=='NDG-A0':
88                    r='csml'
89                    name=self.uri.localID
90                    #for now we'll handle as pretty print xml
91                    c.xml=x.tohtml()
92                    r='content'
93                    c.tab='Display'
94                elif viewFormat=='DIF':
95                    r='dif'
96                    c.doc=DIF.DIF(x.tree,et=1,ndgObj=self.uri)
97                    name=c.doc.name
98                    print c.doc.ndgObject
99                elif viewFormat=='NumSim':
100                    r='numsim'
101                    c.xmlh=x
102                    c.tbinfo=self.__mytb('')
103                    name=x.getText('NS_Name')
104                    c.name=name
105                else:
106                    c.xml=x.tohtml()
107                    r='content'
108            else:
109                name=str(self.uri)
110                if self.format=='xml':
111                    c.xml=x.tohtml()
112                    r='content'
113                    c.tab='Display'
114                elif self.format=='raw':
115                    c.xml=x.xmls
116                    response.headers['Content-Type'] = 'application/xml'
117                    return response.write(c.xml)
118           
119            needed=0
120            if 'lastViewed' not in session: needed=1
121            session['lastViewed']=h.current_url()
122            if needed: c.pageTabs.append(('Display',session['lastViewed']))
123           
124            session.save()
125            code=200
126        else:
127            if x.startswith('<p> Access Denied'):
128                code=401
129            else: code=400
130            c.xml='%s'%x
131            r='error'
132            print c.xml
133           
134        response.status_code = code
135        try:
136            return render(r)
137        except Exception, e:
138            #we may be showing an xml document ... but it could go wrong if
139            #we have crap content ...
140            if isinstance(e, ExpatError):
141                c.xml='<p> XML content is not well formed </p>'
142                c.doc=str(x)
143            else:
144                c.xml='<p> Unexpected error [%s] viewing [%s] </p>'%(str(e),uri)
145                c.doc=''
146            response.status_code = 400
147            return render('error')
148   
149    def askCorrect(self,uri):
150        ''' Provide a form (ajaxaciously) so that a user can correct a metadata record'''
151        status=self.__setup(uri)
152        c.uri=self.uri
153        if status: return response.write(status)
154        return render('correct',fragment=True)
155
156   
157    def correct(self,uri):
158        ''' Receive a correction form to update a record and post it to the holder '''
159        status=self.__setup(uri)
160        if 'ndgSec' not in session:
161            return response.write('Not Logged In')
162        body='Metadata Change Request for %s'%uri
163        payload='<Change><uri>%s</uri><from>%s</from><Contents>%s</Contents></Change>'%(
164            self.inputs['Identifier'],self.inputs['Submitter'],self.inputs['Comment'])
165        name='ChangeRequestFor_%s.xml'%uri
166        status,message=mailer.mailHandler([self.cf.get('DEFAULT','metadataMaintainer'),],
167                       body,body,xmlAttachments=[(payload,name),],
168                       server=self.cf.get('DEFAULT','mailserver'))
169        if status:
170            c.xml='<p>Success: Mail sent to metadata maintainer</p>'
171        else:
172            c.xml=message
173        return render('content')
174       
175
176    def __mytb(self,name):
177        ''' Get the trackback info for this page
178        (can't do it in Kid because it doesn't do substutions in comments) '''
179        s='''<!--
180        <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
181             xmlns:dc="http://purl.org/dc/elements/1.1/"
182             xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
183        <rdf:Description
184            rdf:about="%s"
185            dc:identifier="%s"
186            dc:title="%s"
187            trackback:ping="%s" />
188        </rdf:RDF>
189        -->'''%(self.uri,g.server+h.url_for(),name,g.server+h.url_for(controller="trackback"))
190        return s
Note: See TracBrowser for help on using the repository browser.