Advertisement
Guest User

Untitled

a guest
Aug 4th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.96 KB | None | 0 0
  1. """
  2. DB HELPER module
  3.  
  4.   Just use it like:
  5.  
  6.            >>> from db import DbHelper
  7.            >>> db = DbHelper()
  8.  
  9.        SELECT example - 1 (clear query)
  10.            >>> query = "SELECT * FROM table"
  11.            >>> result = db.fetchone(query)
  12.  
  13.        SELECT example - 2 (query with data)
  14.            >>> query = "SELECT * FROM table WHERE some_column = %s"
  15.            >>> data = "your param"
  16.            >>> result = db.fetchone(query, data)
  17.  
  18.        If you need to fetch some results from same query
  19.        use this case on first query:
  20.            >>> result = db.fetchone(query, data, open_cursor=True)
  21.        and this case on the next one:
  22.            >>> result = db.fetchone(query, data, next_result=True)
  23.        don' forget to close_cursor after all
  24.            >>> db.close_cursor()
  25.  
  26. """
  27. import pymysql
  28. import time
  29. import config
  30. import logging
  31.  
  32. logger = logging.getLogger(__name__)
  33.  
  34.  
  35. class DbHelper:
  36.     """
  37.    Class help to make clean primary code
  38.    It runs all queries, fetches, connects, disconnects, commits etc. within itself :)
  39.  
  40.    """
  41.  
  42.     def __init__(self):
  43.         logger.debug("db: creating DbHelper instance")
  44.         self.connection = self.connect()
  45.         self.cursor = None
  46.  
  47.     def __enter__(self):
  48.         return self
  49.  
  50.     def __exit__(self, exc_type, exc_val, exc_tb):
  51.         self.close()
  52.  
  53.     @staticmethod
  54.     def connect():
  55.         tries = 0
  56.         while tries < 3:
  57.             tries += 1
  58.             try:
  59.                 connection = pymysql.connect(**config.db_settings)
  60.  
  61.             except pymysql.Error as e:
  62.                 logger.error(f"db: can't connect: \n{e}")
  63.                 time.sleep(1)
  64.                 pass
  65.  
  66.             else:
  67.                 logger.debug('db: connection established')
  68.                 return connection
  69.  
  70.         return None
  71.  
  72.     async def get_cursor(self):
  73.         try:
  74.             self.cursor = self.connection.cursor()
  75.  
  76.         except pymysql.Error as e:
  77.             logger.error(f'db error with cursor open: \n{e}')
  78.  
  79.         else:
  80.             logger.debug('db: cursor opened')
  81.             return self.cursor
  82.  
  83.     async def close_cursor(self):
  84.         if self.cursor:
  85.             self.cursor.close()
  86.  
  87.     async def fetchone(self, *args, **kwargs):
  88.         if self.connection and args:
  89.             if self.cursor:  # if cursor is opened
  90.  
  91.                 if kwargs.get('next_result'):  # if you don' need to run query again, just need to fetch next result
  92.                     result = self.cursor.fetchone()
  93.  
  94.                 else:  # if cursor is open but you need to run query again
  95.                     self.cursor.execute(*args)
  96.                     result = self.cursor.fetchone()
  97.  
  98.             elif kwargs.get('open_cursor'):  # if kwarg open_cursor is True - open cursor
  99.                 cursor = await self.get_cursor()
  100.                 await cursor.execute(*args)
  101.                 result = await cursor.fetchone()
  102.  
  103.             else:  # if you need to open temp cursor and close it after fetch
  104.                 with self.connection.cursor() as cursor:
  105.                     cursor.execute(*args)
  106.                     result = cursor.fetchone()
  107.  
  108.             return result
  109.  
  110.     async def fetchall(self, *args, **kwargs):
  111.         if self.connection and args:
  112.             with self.connection.cursor() as cursor:
  113.                 cursor.execute(*args)
  114.                 return cursor.fetchall()
  115.  
  116.     async def update(self, *args, no_commit=None, **kwargs):
  117.         try:
  118.             if self.connection:
  119.                 if args:
  120.                     with self.connection.cursor() as cursor:
  121.                         cursor.execute(*args)
  122.  
  123.                 if no_commit:
  124.                     pass
  125.                 else:
  126.                     self.connection.commit()
  127.  
  128.         except pymysql.Error as e:
  129.             logger.error(f'db: update failed (pysql reason) \n{e}')
  130.             return False
  131.  
  132.         else:
  133.             logger.debug(f'db: update successful')
  134.             return True
  135.  
  136.     async def insert(self, *args, no_commit=None, **kwargs):
  137.         try:
  138.             if self.connection:
  139.                 if args:
  140.                     with self.connection.cursor() as cursor:
  141.                         cursor.execute(*args)
  142.  
  143.                 if no_commit:
  144.                     pass
  145.                 else:
  146.                     self.connection.commit()
  147.  
  148.         except pymysql.Error as e:
  149.             logger.error(f'db: insert failed (pysql reason) \n{e}')
  150.             return False
  151.  
  152.         else:
  153.             logger.debug(f'db: insert successful')
  154.             return True
  155.  
  156.     async def commit(self):
  157.         if self.connection:
  158.             self.connection.commit()
  159.             logger.debug(f'db: commit successful')
  160.  
  161.     async def close(self):
  162.         if self.cursor:
  163.             self.cursor.close()
  164.             logger.debug(f'db: cursor closed')
  165.  
  166.         if self.connection:
  167.             self.connection.close()
  168.             logger.debug(f'db: connection closed')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement