__init__.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. # -*- coding:utf-8 -*-
  2. # 配置文件初始化
  3. # 主要是一些 db 的初始化创建
  4. # 简单 Class 类函数的 初始化
  5. import asyncio
  6. import logging
  7. import os
  8. from configparser import ConfigParser
  9. from logging.handlers import TimedRotatingFileHandler
  10. from os.path import dirname
  11. # import redis as redis
  12. import uvloop
  13. from requests import adapters
  14. from sqlalchemy import create_engine, and_
  15. from sqlalchemy.orm import sessionmaker
  16. adapters.DEFAULT_POOLSIZE = 100000
  17. asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  18. class CfgBaseInit(object):
  19. """
  20. config: 配置文件对象
  21. project_name: 项目名称
  22. start_mode: 项目启动模式
  23. """
  24. __REC_ENGINE = "REC_ENGINE" # 环境变量以REC_ENGINE开头
  25. config = ConfigParser()
  26. config.read(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config", "config.ini"))
  27. # 遍历所有配置,保存为dict
  28. config_dict = {}
  29. for sc in config.sections(): # 循环每个Session
  30. items = config.items(sc) # 返回结果为元组
  31. config_dict[sc] = {}
  32. for it in items: # 循环遍历 每个属性
  33. k, v = it[0], it[1]
  34. config_value = os.getenv("_".join([__REC_ENGINE, sc, k])) # 环境变量中是否存在
  35. if config_value:
  36. print(f"获取到环境变量:{sc}_{k}")
  37. v = config_value
  38. config_dict[sc][k] = v
  39. project_name = config.get("CONFIG", "project_name")
  40. project_path = dirname(dirname(__file__))
  41. bind = config.get("CONFIG", "host")
  42. class Logger(object):
  43. # 日志
  44. log_path = CfgBaseInit.config.get("LOG", "log_path")
  45. when = CfgBaseInit.config.get("LOG", "when")
  46. backupCount = int(CfgBaseInit.config.get("LOG", "backupCount"))
  47. logging.basicConfig(
  48. format='%(asctime)s %(name)s %(process)d %(thread)d %(threadName)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
  49. logger = logging.getLogger(CfgBaseInit.project_name)
  50. logger.setLevel(logging.DEBUG)
  51. # 输出到文件
  52. handler = TimedRotatingFileHandler(log_path, when=when, backupCount=backupCount)
  53. logger.addHandler(handler)
  54. logger = Logger.logger
  55. class SqlEngine(CfgBaseInit):
  56. """ mysql 引擎
  57. """
  58. import pymysql
  59. from urllib.parse import quote_plus
  60. pymysql.install_as_MySQLdb()
  61. mysql_dict = CfgBaseInit.config_dict["MYSQL"]
  62. # 280秒重新连接一次
  63. DBSession = sessionmaker(bind=create_engine(
  64. f"mysql://{mysql_dict['user']}:{quote_plus(mysql_dict['password'])}@{mysql_dict['host']}:{mysql_dict['port']}/{mysql_dict['db']}",
  65. pool_size=2, max_overflow=0, pool_recycle=280))
  66. @classmethod
  67. def add(cls, item):
  68. with cls.DBSession() as se:
  69. se.add(item)
  70. se.commit()
  71. return item.id
  72. @classmethod
  73. def add_all(cls, items):
  74. with cls.DBSession() as se:
  75. se.bulk_save_objects(items)
  76. se.commit()
  77. @classmethod
  78. def query_all(cls, model, filters=None, order_bys=None, offset=None, limit=None):
  79. """
  80. :param limit:
  81. :param offset:
  82. :param order_bys:
  83. order_by(User.name.desc()
  84. :param model:
  85. :param filters:
  86. User.name=='James'
  87. User.name.like('%e%')
  88. User.name.in_(['Kobe', 'James'])
  89. :return:
  90. """
  91. with cls.DBSession() as se:
  92. query = cls.get_query(filters, se, model, order_bys, offset, limit)
  93. return query.all()
  94. @classmethod
  95. def query_page(cls, model, filters, order_bys=None, offset=0, limit=10):
  96. count = cls.query_count(model, filters)
  97. res_list = cls.query_all(model, filters, order_bys, offset, limit)
  98. return {
  99. "count": count,
  100. "list": res_list
  101. }
  102. @classmethod
  103. def query_count(cls, model, filters=None):
  104. with cls.DBSession() as se:
  105. query = cls.get_query(filters, se, model)
  106. return query.count()
  107. @classmethod
  108. def query_first(cls, model, filters=None):
  109. with cls.DBSession() as se:
  110. query = cls.get_query(filters, se, model)
  111. return query.first()
  112. @classmethod
  113. def update(cls, model, filters, dict_new):
  114. with cls.DBSession() as se:
  115. query = cls.get_query(filters, se, model)
  116. res = query.update(dict_new)
  117. se.commit()
  118. return res
  119. @staticmethod
  120. def get_query(filters, se, model, order_bys=None, offset=None, limit=None):
  121. if filters is None:
  122. filters = []
  123. if order_bys is None:
  124. order_bys = []
  125. query = se.query(model)
  126. for _filter in filters:
  127. query = query.filter(_filter)
  128. if len(order_bys) > 0:
  129. query = query.order_by(*order_bys)
  130. if offset:
  131. query = query.offset(offset)
  132. if limit:
  133. query = query.limit(limit)
  134. return query
  135. @classmethod
  136. def delete(cls, model, filters):
  137. with cls.DBSession() as se:
  138. query = cls.get_query(filters, se, model)
  139. res = query.delete()
  140. se.commit()
  141. return res
  142. class RedisInit(CfgBaseInit):
  143. """
  144. Redis 对象初始化
  145. """
  146. # __redis_dict = CfgBaseInit.config_dict["REDIS"]
  147. # __host = __redis_dict['host']
  148. # __port = __redis_dict['port']
  149. # __db = __redis_dict['db']
  150. # pool = redis.ConnectionPool(host=__host, port=__port, db=__db, max_connections=None, decode_responses=True,
  151. # socket_keepalive=False)
  152. # redis = redis.Redis(connection_pool=pool)