source: mauRepo/MolesManager/trunk/cedaMoles/MolesManager/molesSessionMiddleware.py @ 8507

Subversion URL: http://proj.badc.rl.ac.uk/svn/ndg/mauRepo/MolesManager/trunk/cedaMoles/MolesManager/molesSessionMiddleware.py@8507
Revision 8507, 5.5 KB checked in by mnagni, 8 years ago (diff)

Incomplete - # 22534: Add versiojn number to the gui page
 http://team.ceda.ac.uk/trac/ceda/ticket/22534

Line 
1'''
2BSD Licence
3Copyright (c) 2012, Science & Technology Facilities Council (STFC)
4All rights reserved.
5
6Redistribution and use in source and binary forms, with or without modification,
7are permitted provided that the following conditions are met:
8
9    * Redistributions of source code must retain the above copyright notice,
10        this list of conditions and the following disclaimer.
11    * Redistributions in binary form must reproduce the above copyright notice,
12        this list of conditions and the following disclaimer in the documentation
13        and/or other materials provided with the distribution.
14    * Neither the name of the Science & Technology Facilities Council (STFC)
15        nor the names of its contributors may be used to endorse or promote
16        products derived from this software without specific prior written permission.
17
18THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
20THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
22BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
23OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29Created on 9 Jan 2012
30
31@author: Maurizio Nagni
32'''
33from cedaMoles.MolesManager.moles3epb import Moles3EPBFactory
34from cedaMoles.libs.migration.client import MigrationThread
35from cedaMoles.MolesManager.settings import RUN_MIGRATION, MIGRATION_INTERVAL,\
36    MIGRATION_DB_CONNECTION, MIGRATION_DB_SCRIPT, MOLES3_DB_CONNECTION,\
37    MOLES3_DB_SCRIPT, EVENTS_DB, INFO_DB_CONNECTION
38from cedaMoles.libs.commons_db import DbManager
39from cedaMoles.libs.migration.InfodbEPB import InfodbEPBFactory
40from cedaMoles.libs.migration.MigrationEPB import MigrationEPBFactory
41from sqlalchemy import exc
42from django.core.context_processors import csrf
43from django.shortcuts import render_to_response
44from cedaMoles import __version__
45
46
47
48class MolesSessionMiddleware(object):
49   
50    #This attribute should be not here.
51    #unfortunately I cannot find any start/stop signals from Django
52    #_migrationThread = MigrationThread(interval = MIGRATION_INTERVAL)
53    _epbInitialized = False
54    _infodbEPBFactory = None   
55    _moles3EPBFactory = None
56    _migrationEPBFactory = None
57   
58    def _doInitialization(self):
59
60        infoDB = DbManager(INFO_DB_CONNECTION)
61        MolesSessionMiddleware._infodbEPBFactory = InfodbEPBFactory(infoDB)
62           
63        migrationDB = DbManager(MIGRATION_DB_CONNECTION, MIGRATION_DB_SCRIPT)
64        MolesSessionMiddleware._migrationEPBFactory = MigrationEPBFactory(migrationDB)               
65
66        molesDB = DbManager(MOLES3_DB_CONNECTION, MOLES3_DB_SCRIPT, session_event_manager=EVENTS_DB)
67        MolesSessionMiddleware._moles3EPBFactory = Moles3EPBFactory(molesDB)
68       
69        MolesSessionMiddleware._migrationThread = MigrationThread( \
70            MolesSessionMiddleware._moles3EPBFactory.createEPB(), \
71            MolesSessionMiddleware._migrationEPBFactory.createEPB(), \
72            MolesSessionMiddleware._infodbEPBFactory.createEPB(), \
73            interval = MIGRATION_INTERVAL )
74        MolesSessionMiddleware._epbInitialized = True     
75           
76        _migration()
77   
78    def process_request(self, request): 
79        try:
80            if not MolesSessionMiddleware._epbInitialized:
81                self._doInitialization()
82                 
83            request.moles3EPB = MolesSessionMiddleware._moles3EPBFactory.createEPB()                   
84        except exc.DBAPIError, e:
85            # an exception is raised, Connection is invalidated.
86            #if e.connection_invalidated:
87            #    print "Connection was invalidated!"
88            return self.process_exception(request, e)
89
90    def process_response(self, request, response):
91        if hasattr(request, "moles3EPB"):           
92            request.moles3EPB.close()           
93        return response
94
95    def process_exception(self, request, exception):
96        c = {}
97        c['exception'] = exception
98        c.update(csrf(request))
99        return render_to_response('errorTemplate.html', c)
100   
101def _migration(runMigration = RUN_MIGRATION):
102    if runMigration and not MolesSessionMiddleware._migrationThread.isAlive():
103        #t.setDaemon(False)
104        MolesSessionMiddleware._migrationThread.start()   
105       
106
107def mm_render_to_response(request, context, page_to_render):
108    """
109    Exploit a 'render_to_response' action. The advantage of this method
110    is to contains a number of operations that are expected to be  called
111    for each page rendering, for example passing the application version number
112     
113    **Parameters**           
114        * HttpRequest_ **request**
115            a django HttpRequest instance       
116        * `dict` **context**
117            a dictionary where to pass parameter to the rendering function   
118        * `string` **page_to_render**
119            the html page to render                         
120    """
121    if context is None or not isinstance(context, dict):
122        raise Exception("Cannot render an empty context")
123   
124    context['version'] = __version__
125    context.update(csrf(request))
126    return render_to_response(page_to_render, context)           
Note: See TracBrowser for help on using the repository browser.