db_utils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # coding:utf-8
  2. import pymongo
  3. import pymysql
  4. import pymysql.cursors
  5. from django.conf import settings
  6. class MySQLTool:
  7. def __init__(self):
  8. config = settings.CONFIG["bigdatamysql"]
  9. self.conn = pymysql.connect(
  10. host=config['host'], user=config['user'],
  11. password=config['pwd'], port=config['port'],
  12. database='smartfarming', charset='utf8mb4',
  13. cursorclass=pymysql.cursors.DictCursor
  14. )
  15. def execute_by_one(self, sql):
  16. cursor = self.conn.cursor()
  17. cursor.execute(sql)
  18. result = cursor.fetchone()
  19. cursor.close()
  20. if self.conn:
  21. self.conn.close()
  22. return result
  23. class MongoDBTools:
  24. def __init__(self, db_name, table_name):
  25. config = settings.CONFIG["bigdatamongo"]
  26. host, port = config['host'], config['port']
  27. user, password = config['user'], config['pwd']
  28. self.client = pymongo.MongoClient(host=host, port=port, username=user, password=password)
  29. self.db_name = db_name
  30. self.table_name = table_name
  31. self.tb = self.client[self.db_name][self.table_name]
  32. def find_one(self, wheres, options=None, is_reverse=True):
  33. if not options:
  34. options = {}
  35. projection = {'_id': 0}
  36. projection.update(options)
  37. sort = []
  38. if is_reverse:
  39. sort.append(('_id', pymongo.DESCENDING))
  40. result = self.tb.find_one(wheres, projection=projection, sort=sort)
  41. if not result:
  42. result = {}
  43. return result
  44. def find_many(self, wheres, options=None, is_reverse=True, skip=0, limit=0, sort=None):
  45. if not options:
  46. options = {}
  47. projection = {'_id': 0}
  48. projection.update(options)
  49. temp_sort = []
  50. if sort:
  51. temp_sort.extend(sort)
  52. if is_reverse:
  53. temp_sort.append(('_id', pymongo.DESCENDING))
  54. result = self.tb.find(wheres, projection=projection, skip=skip, limit=limit, sort=temp_sort)
  55. if not result:
  56. result = []
  57. return result