source: TI07-MOLES/trunk/PythonCode/wsgi/DiscoveryGUI.py @ 1958

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

Refactoring discovery wsgi for cleaner service binding. (Done, but
there will be implications for wsgi browse which may now be broken,
but I can't test it til the database is updated).

Line 
1import DiscoveryTemplate
2from paste.request import parse_querystring
3import ndgSearch as NS
4from DIF import DIF
5from renderDiscoverySet import renderDiscoverySet
6from DiscoveryState import DiscoveryState
7from Utilities import myConfig
8
9class DiscoveryGUI:
10    ''' This class handles the NDG gui search interface, and is intimately related to the
11    template.py code which provides the gui interface and the variables which need to be populated '''
12   
13    #The key options are either there is content in the inputdictionary, in which case we have a
14    #search to do, and then some results to present, or there is none, in which case we present
15    #an appropriate interface back to the user (remembering that we only produce part of a page,
16    #this can all be embedded in anything else.
17   
18    def __init__(self,environ,config,logger):
19        ''' Takes a dictionary of variables which have been populated by the cgi (or whatever)
20        handler, and tests them for sanity before handing queries off to the NDG backend xqquery
21        web service '''
22       
23        inputs=dict(parse_querystring(environ))
24        self.inputs=inputs
25        self.environ=environ
26        self.config=config
27        self.logger=logger
28
29        self.message=''
30        self.html=''
31       
32        #is this simply a blank request for an interface?
33        if self.inputs.keys()==[]:
34            self.html+='<div id="superPad">'
35            self.standardInterface()
36            self.html+='</div>'
37            return
38        elif self.inputs.keys()==['advanced']:
39            self.advancedInterface()
40            return
41        elif self.inputs.keys()==['help']:
42            self.helpInterface(0)
43            return
44        elif self.inputs.keys()==['help','advanced']:
45            self.helpInterface(1)
46            return
47       
48        #check simplest text issues common to both simple and advanced search
49        expected=['advanced','textTarget','searchString']
50        self.__checkform(expected)
51        if self.message!='': return
52       
53        #the following may also be present
54        continuations={'start':1,'howmany':10}
55        for i in continuations:
56            if i not in self.inputs: self.inputs[i]=continuations[i]
57           
58        advanced=int(self.inputs['advanced'])
59       
60        self.html=''
61        if not advanced:
62            self.doText(self.inputs['searchString'],self.inputs['textTarget'],
63                        self.inputs['start'],self.inputs['howmany'])
64        else:
65            #check content
66            expected=['timeLimit','startDateDay','startDateMon','startDateYear',
67                        'endDateDay','endDateMon','endDateYear','spaceLimit',
68                        'bboxN','bboxE','bboxS','bboxW',
69                        'sourceLimit']
70            self.__checkform(expected)
71            if self.message!='': return
72             
73            if int(self.inputs['sourceLimit']):
74                scope=[]
75                if 'sourceMDIP' in self.inputs:
76                    if self.inputs['sourceMDIP']: scope.append('MDIP')
77                if 'sourceNERC' in self.inputs:
78                    if self.inputs['sourceNERC']: scope.append('NERC')
79            else:
80                scope=None
81               
82            if int(self.inputs['spaceLimit']):
83                bbox=[self.inputs['bboxN'],self.inputs['bboxS'],self.inputs['bboxW'],self.inputs['bboxE']]
84            else:
85                bbox=None
86               
87            if int(self.inputs['timeLimit']):
88                dateRange=[(self.inputs['startDateDay'],self.inputs['startDateMon'],self.inputs['startDateYear']),
89                           (self.inputs['endDateDay'],self.inputs['endDateMon'],self.inputs['endDateYear'])]
90            else:
91                dateRange=None
92               
93            self.doText(self.inputs['searchString'],self.inputs['textTarget'],
94                        self.inputs['start'],self.inputs['howmany'],scope=scope,dateRange=dateRange,bbox=bbox)
95           
96        return
97           
98    def __checkform(self,expected):
99        ''' Simply checks the inputs to make sure the elements in expected are present '''
100        message="An incomplete NDG search form was received: "
101        for i in expected:
102            if i not in self.inputs: 
103                self.message=message+i
104                self.html='<p>%s</p>'%self.message
105               
106    def __setState(self,id,hits,offset,stride):
107        ''' Sets the discovery state to be used by external routines '''
108        return DiscoveryState(id,self.environ,hits,offset,stride)
109       
110    def doText(self,searchString,textTarget,start,howmany,scope=None,dateRange=None,bbox=None):
111        ''' Carry out a text search for <searchString>
112        in the <textTarget> where the accepted text target values are controlled
113        by the DiscoveryTemplate GUI, and are: All, Authors, Parameters '''
114       
115        start,howmany=int(start),int(howmany)  # url arguments need conversion ...
116       
117        ws=NS.ndgSearch(logger=self.logger)
118        documents=ws.search(searchString,start=start,howmany=howmany,target=textTarget,
119                            scope=scope,dateRange=dateRange,bbox=bbox)
120        if ws.error !=None:
121            for i in ws.error:
122                self.html+='<p>%s</p>'%i
123            return
124       
125        hits=ws.hits
126        id=ws.serverSessionID
127        state=self.__setState(id,hits,start,howmany)
128        if hits==0: 
129            self.html+='<p> No records found </p>'
130        else:
131            results=ws.getLabelledDocs()
132            difs=[]
133            for result in results: 
134                url='%s?%s=%s'%(self.config.get('DISCOVERY','default'),
135                self.config.get('DISCOVERY','instance'),result[0])
136                difs.append(DIF(result[1],url=url))
137            if results==[]:
138               self.html+='<p>No results for "%s"!</p>'%searchString
139            else:
140               self.html+='<p>Search results for "%s":</p>'%searchString
141               self.html+=renderDiscoverySet(difs,state,config=self.config,
142                               summary=1,spatial=1,temporal=1,services=1)
143                               
144        self.standardInterface()
145        return
146
147    def standardInterface(self):
148       
149        try:
150            helpAddress=self.config.get('SEARCH','helpURL')
151            discoveryURL=self.config.get('SEARCH','discoveryURL')
152            advancedURL=self.config.get('SEARCH','advancedURL')
153        except:
154            self.message='Error, invalid configuration for search interface'
155            self.html+=''
156            return
157       
158        self.html+=DiscoveryTemplate.main%locals()
159        return
160   
161    def advancedInterface(self):
162       
163        try:
164            helpAddress=self.config.get('SEARCH','helpURL')
165            discoveryURL=self.config.get('SEARCH','discoveryURL')
166            advancedURL=self.config.get('SEARCH','advancedURL')
167        except:
168            self.message='Error, invalid configuration for search interface'
169            self.html=''
170            return
171        advancedSubmit=DiscoveryTemplate.advancedSubmit%locals()
172        searchText=DiscoveryTemplate.searchText
173        searchTime=DiscoveryTemplate.searchTime
174        searchArea=DiscoveryTemplate.searchArea
175        searchSource=DiscoveryTemplate.searchSource
176        self.html+=DiscoveryTemplate.advanced%locals()
177        return
178   
179    def helpInterface(self,advanced):
180        if advanced:
181            self.advancedInterface()
182        else:
183            self.standardInterface()
184        helpFile=self.config.get('HELP','helpFile')
185        f=file(helpFile,'r')
186        self.html+=f.read()
187        return
188       
189       
Note: See TracBrowser for help on using the repository browser.