source: TI07-MOLES/trunk/PythonCode/wsgi/ndgRetrieve.py @ 2097

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/trunk/PythonCode/wsgi/ndgRetrieve.py@2097
Revision 2097, 5.6 KB checked in by lawrence, 12 years ago (diff)

Sundry modifications associated with the deployment on glue, and better
options for viewing and downloading the underlying xml records (not yet
complete)

Line 
1from Utilities import myConfig
2from paste.request import parse_querystring
3from renderEntity import renderEntity
4import xmlHandler
5from DC import DC
6from DIF import DIF
7from stubB import stubB
8from ndgObject import ndgObject
9
10# any class with a get method can be used here, and then only
11# the instantiation within ndgRetrieve would need
12# modification to use it ...
13
14from DocumentRetrieve import DocumentRetrieve
15
16def retrieveFactory(global_config,**local_conf):
17   
18    ''' This factory is intended to be used by paste-deploy to return
19    the ndgRetrieve wsgi application, configured to use the configDir
20    to find local configuration information '''
21   
22    if 'configDir' in local_conf.keys():
23        configDir=local_conf[configDir]
24    else:
25        try:
26            configDir=global_config['configDir']
27        except:
28            configDir=None
29    ndg=ndgRetrieve(configDir)
30    return ndg
31
32class showDoc:
33    ''' Given an xml document (xml), of format ('DIF','DC','NDG-B1'), return
34    either the document rendered as "pretty" xml for printing, or as html
35    rendered by an appropriate application'''
36   
37    def __init__(self,config):
38        self.config=config
39        self.renderer=renderEntity(self.config)
40       
41    def get(self,xml,format,otype='html'):
42        if otype=='html':
43            if format=='DIF':
44                r=DIF(xml)
45            elif format=='NDG-B1':
46                r=stubB(xml,self.config)
47            elif format=='DC':
48                r=DC(xml)
49            r=self.renderer.render(r)
50        elif otype=='print':
51            x=xmlHandler.xmlHandler(xml,string=1)
52            r=x.html
53        elif otype=='xml':
54            return xml
55        else:
56            raise TypeError('Invalid output type [%s]'%otype)
57        return r
58
59class ndgRetrieve:
60   
61    ''' This is the ndgRetrieve application which simply allows one to enter a uri
62    of a document held in a LOCAL exist repository and return one of
63       - the raw document (type=xml),
64       - an html version fully rendered (type=html, which is the default), or
65       - a pretty printed version suitable for printing (type=print)
66    Note that this WSGI application SHOULD be wrapped by an ndgGatekeeper MIDDLEWARE application and
67    not exposed directly to users (except in testing of course :-) '''
68   
69    def __init__(self,configDir):
70       
71        ''' Instantiate the wsgi document retrieval application '''
72        self.configDir=configDir
73        self.config=myConfig(configDir+'ndgDiscovery.config')
74        self.shower=showDoc(self.config)
75        # nb ... we don't instantiate the retrieval web service, since
76        # we expect to potentially have multiple web services pointing
77        # at multiple databases (eg. BADC + NEODC + NDG ) ...
78        self.retrieveWS=DocumentRetrieve
79        self.WScursors={}
80   
81    def __call__(self,environ,start_response):
82       
83        ''' This is the function which implements the document retrieval '''
84       
85        inputs=dict(parse_querystring(environ))
86        #print inputs
87       
88        ctype='text/html'   # default content type (since the default
89                            # may be an error return ...) the actual default
90                            # data type for return is xml.
91        if 'uri' not in inputs.keys():
92            r=self.__prompt()
93            raise ValueError,r
94        else:
95            #this will raise a ValueError if there is a problem
96            uri=ndgObject(inputs['uri'])
97            if 'repository' in inputs.keys(): 
98                db=inputs['repository']
99            else:
100                db=uri.repository
101            if db in self.WScursors.keys():
102                ws=self.WScursors[db]
103            else:
104                ws=DocumentRetrieve(db)
105                self.WScursors[db]=ws
106            ok=1
107            try:
108                if 'format' not in inputs.keys():
109                    format='NDG-B0'
110                else:
111                    format=inputs['format']
112                r=ws.get(uri.repository,uri.schema,uri.localID,format=format)
113                if isinstance(r,int):
114                     r='<p> There are %s identifiers matching your request! </p>'%r
115                     ok=0
116            except Exception,e:
117                 r='<p> Unable to retrieve [%s], reason was [%s]</p>'%(uri,e)
118                 ok=0
119            if ok:
120                try:
121                    outputType=inputs['type']
122                except KeyError:
123                    outputType='print'
124                if outputType!='xml': 
125                    try:
126                        r=self.shower.get(r,format,otype=outputType)
127                    except Exception,e:
128                        r='<p> Unable to show document, reason was [%s]<p>'%e
129                else:
130                    ctype='text/xml'
131            start_response('200 OK', [('Content-Type', ctype)])
132        return [r]   
133               
134   
135   
136    def __prompt(self):
137        ''' If the URI is not an argument to the request, prompt the user for a URI '''
138        h='''
139        <form method='get' action=''>
140        <p>
141          Enter a Document Identifier to View: 
142            <input type='text' name='uri'/><br/>
143            (uri format: e.g. badc.nerc.ac.uk:DIF:xyz39) <br/>
144            (Querying <input type='text' name='repository' value='gepidae.esc.rl.ac.uk'/>)<br/>
145            Return: <input type="radio" name="type" value="xml"/> XML Raw
146                <input type="radio" name="type" value="html"/> Formatted
147                <input type="radio" name="type" value="print"/> XML Printable
148          <input type='submit'/>
149        </p>
150        </form>
151        '''
152        return h
153   
154   
Note: See TracBrowser for help on using the repository browser.