source: TI07-MOLES/tags/wsgi-beta/ndgPageLayout.py @ 2608

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/TI07-MOLES/tags/wsgi-beta/ndgPageLayout.py@2608
Revision 2608, 9.7 KB checked in by lawrence, 13 years ago (diff)

Tagging the current version of wsgi PythonCode? (discovery/browse) as
beta - even though there are some issues still to be sorted ...

Line 
1from Utilities import myConfig,mailError
2from paste.request import parse_querystring, construct_url
3from ndgSelector import ndgSelector
4
5debug=1
6def DiscoveryFrameFactory(global_config,**local_conf):
7   
8    ''' This factory is intended to be used by paste-deploy to return
9    the discovery FRAME wsgi MIDDLEWARE application, configured to use the configDir
10    to find local configuration information '''
11   
12    if 'configDir' in local_conf.keys():
13        configDir=local_conf[configDir]
14    else:
15        try:
16            configDir=global_config['configDir']
17        except:
18            configDir=None
19           
20    configFile=configDir+'ndgDiscovery.config'
21   
22    def filter(app):
23        return DiscoveryFrame(app,'NERC DataGrid: Data Portal',configFile)
24   
25    return filter
26
27class DiscoveryFrame(object):
28     
29    def __init__(self, wrapTarget,pageName,configFile=None):
30       
31        ''' This is simple WSGI middleware to provide a page wrapper, will eventually
32        include cookie handling for grabbing a "cart" of datasets '''
33       
34        self.wrapTarget=wrapTarget
35        self.config=myConfig(configFile)
36       
37        helpAddress=self.config.get('SEARCH','helpURL')
38        ndgJavascript=self.config.get('layout','ndgJavascript')
39        self.mailServer=self.config.get('DEFAULT','mailServer','outbox.rl.ac.uk')
40        self.server=self.config.get('DEFAULT','server','CONFIG-FILE-ERROR')
41
42        self.pageStart='''
43        <?xml version="1.0" encoding="utf-8"?>
44            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
45            "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
46            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
47                <head>
48                  <meta http-equiv="Content-Type" content="text/xhtml; charset=utf-8"/>
49                  <title>%s</title>
50                  <link media="all, screen" href="layout/ndg.css" type="text/css" rel="stylesheet"/>
51                  <script type="text/javascript" src="%s"/>
52                </head><body><div id="Main">'''%(pageName,ndgJavascript)
53       
54        self.header='''<div id="Header">%s</div>'''% self.__buildHeader(configFile)
55
56    def __call__(self,environ,start_response):
57        ''' Let's prepend and postpend some stuff'''
58        self.url=construct_url(environ)
59        inputs=parse_querystring(environ)
60        if ('type','xml') in inputs:
61            response='''<?xml version="1.0" encoding="utf-8"?>'''
62            footer=0
63        else:
64            footer=1
65            response=self.pageStart+self.header
66           
67        #  Note that build footer will remove any ndg security info from the query string as well as set self.loginstatus
68        self.inputs=dict(inputs)
69        environ,self.footer=self.__buildFooter(environ)
70       
71        #try:
72        if debug:
73            wrapped=self.wrapTarget(environ,start_response)
74        else:
75            wrapped=str(self.wrapTarget(environ,start_response))
76        failure=0
77        #except Exception,e:
78        #    raise Exception,e
79        #    body='Error [%s]\n'%e
80        #    wrapped=['''<p> Unable to fufill request. NDG staff have been advised.
81        #    Please try another search. </p><p>%s</p> '''%body]
82        #    body+=str(environ)
83        #    mailError('b.n.lawrence@rl.ac.uk','Discovery/Browse Error',body,server=self.mailServer)
84        #    failure=1
85        sidebar=''
86       
87        if self.loginstatus:
88            # top left right bottom layout
89            HistoryContent=environ['ndgSelector'].getHistoryHTML()
90            CartContent=environ['ndgSelector'].getCartHTML()
91            sidebar=self.__buildLeftPanel(HistoryContent,CartContent)
92            h='%s <div id="CentralPane">%s<div id="Contents">%s</div></div>%s'%(response,sidebar,wrapped[0],self.footer)
93        else:
94            # top middle bottom layout
95            h=response+wrapped[0]
96            if footer: h+=self.footer
97        if failure: start_response('500 OK', [('Content-Type', 'text/html'),('charset','utf-8')])
98        #currently need to coerce response into a string for flup ...
99        return [h]
100       
101    def __buildHeader(self,configFile):
102       
103        if configFile is None: return ''
104        config=myConfig(configFile)
105        localLink=config.get('layout','localLink',None)
106        localImage=config.get('layout','localImage',None)
107        localAlt=config.get('layout','localAlt','Visit Local Site')
108        ndgLink=config.get('layout','ndgLink','http://ndg.nerc.ac.uk')
109        ndgImage=config.get('layout','ndgImage',None)
110        ndgAlt=config.get('layout','ndgAlt','Visit NDG')
111        PageLogo=config.get('layout','pageLogo',None)
112       
113        banner='''   
114            <table cellpadding="0" cellspacing="0" width="100%%">
115            <tbody><tr>
116            <td width="10%%" align="center" valign="middle">
117              <a href="%s"> <img src="%s" alt="%s"/> </a> </td>
118            <td width="80%%" align="center" valign="middle" >
119              Natural Environment Research Council<br/>
120              Data Discovery Service</td>
121            <td width="10%%" align="center" valign="middle">
122              <a href="%s"> <img src="%s" alt="%s"/> </a> </td>
123            </tr>
124            </tbody></table>'''%(ndgLink,ndgImage,ndgAlt,localLink,localImage,localAlt)
125       
126        return banner
127       
128       
129    def __buildFooter(self,environ):
130        ''' Return a footer which includes a login button '''
131        left='''<p> This portal is a product of the <a href="http://ndg.nerc.ac.uk"> NERC DataGrid</a>. Not all functionality is completely implemented, bugs and problems are expected </p>'''
132        environ,right=self.__loginStatus(environ)
133        if self.loginstatus:
134            environ['ndgSelector']=ndgSelector(environ,url=self.url)
135        else:
136            environ['ndgSelector']=None
137       
138        return environ,'''
139        <div id="Footer"><center><table><tbody>
140            <tr><td align="center" width="50%%">%s</td>
141                <td width="50%%" align="center">%s</td>
142            </tr></tbody></table></center></div>'''%(left,right)
143   
144    def __loginStatus(self,environ):
145        ''' This should eventually talk to a cookie &/or redirect ... '''
146        if 'ndg1' in self.inputs:
147            #it is a redirect, handle, and write to cooke ...
148            ndg1=self.inputs['ndg1']
149            ndg2=self.inputs['ndg2']
150            loginstatus=True
151            #now we need to fix up the query string so that nothing else needs know about this ...
152            del self.inputs['ndg1']
153            del self.inputs['ndg2']
154            # build a new query string
155            environ['QUERY_STRING']=dict2querystring(self.inputs)
156            # and clear the parsed querystring cache
157            del environ['paste.parsed_querystring']
158            # now get this stuff into the response as a cookie
159            environ['ndgSecurity']=[ndg1,ndg2]
160        else:
161            # get status from cookie
162            loginstatus=False
163        loginhost='badc'
164        currentPage=self.url
165        if loginstatus:
166            logout='''<a class="button" href="%s">logout</a>'''%currentPage
167            loginMessage='You are logged in at %s: %s'%(loginhost,logout)
168        else:
169            login='''<a class="button" href="%s/login?loginfrom=%s">login</a>'''%(self.server,currentPage)
170            loginMessage='Further services may be available if you can %s'%login
171        self.loginstatus=loginstatus
172        return environ,loginMessage
173       
174    def __buildLeftPanel(self,HistoryContent,CartContent):
175        ''' The left panel holds a history and shopping cart '''
176        # (Start with styles as you wish to look at it before the user has clicked on anything)
177        h='''
178        <div id="HistoryCart"><table border="0" cellpadding="0" cellspacing="0">
179        <tbody>
180            <tr>
181                <td align="left">
182                    <div id="TabHistoryFocus" class="tab tabfocus" style="display:block;">
183                    History
184                    </div>
185                    <div id="TabHistoryReady" class="tab tabhold" style="display:none;">
186                    <!-- Between the parenthesis, provide a list of ids that are to
187                         be visible when this tab is clicked. The ids are between
188                         single quotes (apostrophes) and separated with a comma. -->
189                    <span onclick="ManageTabPanelDisplay('TabHistoryFocus','TabCartReady','HistoryContent')">History</span>
190                    </div>
191                </td><td width="10"></td><td align="right">
192                    <div id="TabCartFocus" class="tab tabfocus" style="display:none;">
193                    Selected
194                    </div>
195                    <div id="TabCartReady" class="tab tabhold" style="display:block;">
196                    <!-- Between the parenthesis, provide a list of ids that are to
197                        be visible when this tab is clicked. The ids are between
198                        single quotes (apostrophes) and separated with a comma. -->
199                    <span onclick="ManageTabPanelDisplay('TabHistoryReady','TabCartFocus','CartContent')">Selected</span>
200                    </div>
201                </td>
202            </tr>
203            <tr><td colspan="3">
204                <div id="HistoryContent" class="tabcontent" style="display:block;">
205                %s
206                </div>
207                <div id="CartContent" class="tabcontent" style="display:none;">
208                %s
209                </div>
210            </td></tr>
211        </tbody>
212        </table></div>
213        '''%(HistoryContent,CartContent)
214        return h
215       
216def dict2querystring(adictionary):
217    ''' Take a dictionary and construct an http query string '''
218    #nb whether or not it is url safe is irrelevant since we're handling it the same way it came.
219    s=''
220    for k in adictionary:
221        s+='%s=%s&'%(k,adictionary[k])
222    if s<>'': s=s[:-1] # strip last &
223    return s
Note: See TracBrowser for help on using the repository browser.