1 | ''' |
---|
2 | Created on 9 Jan 2012 |
---|
3 | |
---|
4 | @author: mnagni |
---|
5 | ''' |
---|
6 | from MolesManager.moles3epb import Moles3EPB |
---|
7 | from libs.migration.client import MigrationThread |
---|
8 | from MolesManager.settings import RUN_MIGRATION, MIGRATION_INTERVAL,\ |
---|
9 | MIGRATION_DB_CONNECTION, MIGRATION_DB_SCRIPT, MOLES3_DB_CONNECTION,\ |
---|
10 | MOLES3_DB_SCRIPT |
---|
11 | from libs.commons_db import DbManager |
---|
12 | from libs.migration.MigrationEPB import MigrationEPB |
---|
13 | |
---|
14 | |
---|
15 | class MolesSessionMiddleware(object): |
---|
16 | |
---|
17 | #This attribute should be not here. |
---|
18 | #unfortunately I cannot find any start/stop signals from Django |
---|
19 | _migrationThread = MigrationThread(interval = MIGRATION_INTERVAL) |
---|
20 | _epbInitialized = False |
---|
21 | |
---|
22 | |
---|
23 | |
---|
24 | def _getMolesSession(self): |
---|
25 | if not MolesSessionMiddleware._epbInitialized: |
---|
26 | migrationDB = DbManager(MIGRATION_DB_CONNECTION, MIGRATION_DB_SCRIPT) |
---|
27 | MigrationEPB.overrrideDBManager(migrationDB) |
---|
28 | |
---|
29 | molesDB = DbManager(MOLES3_DB_CONNECTION, MOLES3_DB_SCRIPT) |
---|
30 | Moles3EPB.overrrideDBManager(molesDB) |
---|
31 | MolesSessionMiddleware._epbInitialized = True |
---|
32 | return Moles3EPB.getNewMolesSession() |
---|
33 | else: |
---|
34 | return Moles3EPB.getNewMolesSession() |
---|
35 | |
---|
36 | def _migration(self, runMigration = RUN_MIGRATION): |
---|
37 | if runMigration and not MolesSessionMiddleware._migrationThread.isAlive(): |
---|
38 | #t.setDaemon(False) |
---|
39 | MolesSessionMiddleware._migrationThread.start() |
---|
40 | |
---|
41 | """ |
---|
42 | Represents the access to the Moles database. |
---|
43 | Creates from the existing db connections pools a new session |
---|
44 | to be used by all the DB operations involved in the actual HTTPRequest |
---|
45 | """ |
---|
46 | |
---|
47 | def process_request(self, request): |
---|
48 | self._migration() #see the note on MolesSessionMiddleware._migration |
---|
49 | |
---|
50 | request.moles_session = self._getMolesSession() |
---|
51 | |
---|
52 | |
---|
53 | def process_response(self, request, response): |
---|
54 | if hasattr(request, 'moles_session'): |
---|
55 | request.moles_session.close() |
---|
56 | |
---|
57 | return response |
---|
58 | |
---|
59 | |
---|
60 | def process_exception(self, request, exception): |
---|
61 | try: |
---|
62 | session = request.moles_session |
---|
63 | except AttributeError: |
---|
64 | return |
---|
65 | session.rollback() |
---|
66 | session.close() |
---|