Last active
August 29, 2015 14:11
-
-
Save danielepantaleone/5a81f9863eececd67a4e to your computer and use it in GitHub Desktop.
DatabaseStorage.context_query
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from contextlib import contextmanager | |
@contextmanager | |
def context_query(self, query, bindata=None): | |
""" | |
Alias for DatabaseStorage.query which can make use of the python 'with' statement. | |
The contextmanager approach ensures that the generated DatabaseStorage.Cursor object instance | |
is always closed whenever the execution goes out of the 'with' statement block. | |
Example: | |
>> with DatabaseStorage.query(q) as cursor: | |
>> if not cursor.EOF: | |
>> cursor.getRow() | |
>> ... | |
:param query: The query to execute. | |
:param bindata: Data to bind to the given query. | |
""" | |
if self.db or self.connect(): | |
cursor = None | |
try: | |
cursor = self._query(query, bindata) | |
yield cursor | |
except Exception, e: | |
self.console.error('[%s] %r: %s' % (query, bindata, e)) | |
if e[0] == 2013 or e[0] == 2006: | |
# if the error was due to SQL server gone away, try to reconnect and execute the query again | |
self.console.warning('Query failed: trying to reconnect - %s: %s' % (type(e), e)) | |
if self.connect(): | |
try: | |
cursor = self._query(query, bindata) | |
yield cursor | |
except Exception: | |
# can't execute one more time so just log the error message | |
self.console.error('[%s] %r: %s' % (query, bindata, e)) | |
finally: | |
if cursor: | |
cursor.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment