11
22from sqlalchemy .exc import SQLAlchemyError , DBAPIError
33from sqlalchemy import create_engine
4- from sqlalchemy .orm import sessionmaker
4+ from sqlalchemy .orm import sessionmaker , scoped_session
55
66from odm2api .ODM2 .models import Variables as Variable2 , setSchema
77
1515
1616class SessionFactory ():
1717 def __init__ (self , connection_string , echo = True , version = 2.0 ):
18+
1819 if 'sqlite' in connection_string :
1920 self .engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo )
2021 self .test_engine = self .engine
21-
2222 elif 'mssql' in connection_string :
23- import pyodbc
24- self .engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 )
25- self . test_engine = create_engine ( connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 , connect_args = {'timeout' : 1 })
23+ self . engine = create_engine ( connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 )
24+ self .test_engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 ,
25+ connect_args = {'timeout' : 1 })
2626 elif 'postgresql' in connection_string or 'mysql' in connection_string :
27- self .engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 , pool_timeout = 5 , pool_size = 20 , max_overflow = 0 )
28- self .test_engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 , pool_timeout = 5 , max_overflow = 0 , connect_args = {'connect_timeout' : 1 })
27+ self .engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 ,
28+ pool_timeout = 1000 , pool_size = 20 , max_overflow = 0 )
29+ self .test_engine = create_engine (connection_string , encoding = 'utf-8' , echo = echo , pool_recycle = 3600 ,
30+ pool_timeout = 5 , max_overflow = 0 , connect_args = {'connect_timeout' : 1 })
2931
3032 # Create session maker
31- self .Session = sessionmaker (bind = self .engine , autoflush = True )
32- self .test_Session = sessionmaker (bind = self .test_engine )
33+ self .Session = scoped_session ( sessionmaker (bind = self .engine , autoflush = True ) )
34+ self .test_Session = scoped_session ( sessionmaker (bind = self .test_engine ) )
3335 setSchema (self .engine )
3436 self .version = version
3537
3638 def getSession (self ):
3739 return self .Session ()
3840
3941 def __repr__ (self ):
40- return "<SessionFactory('%s')>" % ( self .engine )
42+ return "<SessionFactory('%s')>" % self .engine
4143
4244
4345class dbconnection ():
@@ -48,88 +50,84 @@ def __init__(self, debug=False):
4850 self ._connection_format_nopassword = "%s+%s://%s@%s/%s"
4951
5052 @classmethod
51- def createConnection (self , engine , address , db = None , user = None , password = None , dbtype = 2.0 , echo = False ):
53+ def createConnection (self , engine , address , db = None , user = None , password = None , dbtype = 2.0 , echo = False ):
5254
5355 if engine == 'sqlite' :
54- connection_string = engine + ':///' + address
56+ connection_string = engine + ':///' + address
5557 return self .createConnectionFromString (connection_string , dbtype , echo )
5658
5759 else :
5860 connection_string = dbconnection .__buildConnectionString (dbconnection (), engine , address , db , user , password )
5961 if self .isValidConnection (connection_string , dbtype ):
6062 return self .createConnectionFromString (connection_string , dbtype , echo )
61- else :
63+ else :
6264 return None
63- # if self.testConnection(connection_string):
64-
6565
6666 @classmethod
67- def createConnectionFromString (self , conn_string , dbtype = 2.0 , echo = False ):
67+ def createConnectionFromString (self , conn_string , dbtype = 2.0 , echo = False ):
6868 s = SessionFactory (conn_string , echo = echo , version = dbtype )
6969 return s
7070
7171 @classmethod
7272 def isValidConnection (self , connection_string = None , dbtype = 2.0 ):
73- #refreshDB(dbtype)
73+ # refreshDB(dbtype)
7474 if dbtype == 2.0 :
7575 if self .testEngine (connection_string ):
76- # print "sucess"
77- return True
76+ return True
7877 else :
7978 return False
8079 else :
8180 if self .testEngine1_1 (connection_string ):
82- # print "sucess"
8381 return True
8482 else :
8583 return False
8684
8785 @classmethod
88- def testEngine (self , connection_string , echo = False ):
89- s = SessionFactory (connection_string , echo = echo , version = 2.0 )
86+ def testEngine (self , connection_string , echo = False ):
87+ s = SessionFactory (connection_string , echo = echo , version = 2.0 )
9088 try :
9189 setSchema (s .test_engine )
9290 s .test_Session ().query (Variable2 .VariableCode ).limit (1 ).first ()
9391
9492 except Exception as e :
9593 print ("Connection was unsuccessful " , e .message )
9694 return False
95+ finally :
96+ dbconnection .closeConnection (s .test_Session )
9797 return True
9898
9999 @classmethod
100- def testEngine1_1 (self , connection_string , echo = False ):
101- s = SessionFactory (connection_string , echo = echo , version = 1.1 )
100+ def testEngine1_1 (self , connection_string , echo = False ):
101+ s = SessionFactory (connection_string , echo = echo , version = 1.1 )
102102 try :
103- # s.ms_test_Session().query(Variable1).limit(1).first()
104103 s .test_Session ().query (ODM .Variable .code ).limit (1 ).first ()
105104
106105 except Exception as e :
107106 print ("Connection was unsuccessful " , e .message )
108107 return False
108+ finally :
109+ dbconnection .closeConnection (s .test_Session )
109110 return True
110111
112+
111113 @classmethod
112114 def buildConnectionString (self , engine , address , db , user , password ):
113115 return dbconnection .__buildConnectionString (dbconnection (), engine , address , db , user , password )
114116
115-
116-
117-
118- ## ###################
117+ @ classmethod
118+ def closeConnection ( self , session ):
119+ session . remove ()
120+ # # ###################
119121 # private variables
120- ## ###################
121-
122+ # # ###################
122123
123124 def __buildConnectionString (self , engine = None , address = None , db = None , user = None , password = None ):
124125
125126 if engine == 'mssql' and sys .platform != 'win32' :
126127 driver = "pyodbc"
127128 quoted = urllib .quote_plus ('DRIVER={FreeTDS};DSN=%s;UID=%s;PWD=%s;' % (address , user , password ))
128- # quoted = urllib.quote_plus('DRIVER={FreeTDS};DSN=%s;UID=%s;PWD=%s;DATABASE=%s' %
129- # (conn_dict['address'], conn_dict['user'], conn_dict['password'],conn_dict['db'],
130- # ))
131129 conn_string = 'mssql+pyodbc:///?odbc_connect={}' .format (quoted )
132- elif engine == 'sqlite' :
130+ elif engine == 'sqlite' :
133131 driver = 'sqlite'
134132 conn_string = "%s:///%s" % (driver , address )
135133 else :
@@ -151,7 +149,7 @@ def __buildConnectionString(self, engine=None, address=None, db=None, user=None,
151149
152150 return conn_string
153151
154- def constringBuilder (self , engine = None , address = None , db = None , user = None , password = None , driver = None ):
152+ def constringBuilder (self , engine = None , address = None , db = None , user = None , password = None , driver = None ):
155153 if password is None or not password :
156154 conn_string = self ._connection_format_nopassword % (
157155 engine , driver , user , address , db )
0 commit comments