Skip to content

Instantly share code, notes, and snippets.

@danielepantaleone
Last active August 29, 2015 14:11
Show Gist options
  • Save danielepantaleone/5a81f9863eececd67a4e to your computer and use it in GitHub Desktop.
Save danielepantaleone/5a81f9863eececd67a4e to your computer and use it in GitHub Desktop.
DatabaseStorage.context_query
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