ionutHulub

DatabaseConnection

May 26th, 2013
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.28 KB | None | 0 0
  1. """
  2. This is a wrapper over the database. It is responsible
  3. for setting up the connection and executing querys
  4.  
  5. """
  6. __author__ = 'Ionut'
  7. __version__ = '1.0'
  8.  
  9. import redis
  10.  
  11.  
  12. class Database():
  13.     """
  14.    This is a singleton class that can be used
  15.    to communicate with the database
  16.  
  17.    """
  18.     _connection = None
  19.  
  20.     def __init__(self):
  21.         """
  22.        Responsible for connecting to the database
  23.        if a connection is not already present
  24.  
  25.        """
  26.         if Database._connection is None:
  27.             Database._connection = self._connect()
  28.  
  29.     def _connect(self):
  30.         """
  31.        Connects to the database
  32.  
  33.        """
  34.         while True:
  35.             connection = redis.StrictRedis()
  36.             if self._test_connection(connection) == 0:
  37.                 break
  38.         return connection
  39.  
  40.     def _test_connection(self, connection):
  41.         """
  42.        Checks if the connection the the redis database
  43.        was successfull
  44.  
  45.        """
  46.         try:
  47.             connection.set('test', 'test')
  48.         except redis.ConnectionError:
  49.             return -1
  50.         return 0
  51.  
  52.     def get_connection(self):
  53.         """
  54.        Returns an object that can be used to interact
  55.        with the database
  56.  
  57.        """
  58.         return self._connection
Advertisement
Add Comment
Please, Sign In to add comment