import os
from sqlalchemy import create_engine
import datetime


class sql_engine():
    def __init__(self, db, db_name=None, echo=False):
        """
        给出数据库名字，创建数据库连接
        :param db:
        :param db_name:
        :param echo:
        """
        try:
            import Configparser
            self.cf = Configparser.ConfigParser()
        except:
            import configparser
            self.cf = configparser.ConfigParser()
        self.cf.read(os.path.join(os.path.split(os.path.realpath(__file__))[0], 'mysql_config.ini'))
        host = self.cf.get(db, 'host')
        user = self.cf.get(db, 'user')
        passwd = self.cf.get(db, 'passwd')
        port = int(self.cf.get(db, 'port'))
        if not db_name:
            db_name = self.cf.get(db, 'db')
        try:
            self.__engine = create_engine(
                'mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8' % (user, passwd, host, port, db_name), echo=echo,
                connect_args={'connect_timeout': 3600})
        except:
            self.__engine = create_engine(
                'mysql+pymysql://%s:%s@%s:%s/%s?charset=utf8' % (user, passwd, host, port, db_name), echo=echo,
                connect_args={'connect_timeout': 3600})

    def get_engine(self):
        return self.__engine


if 'echo' not in vars():
    echo = False

engine_feature = sql_engine('xyqb_feature', 'xyqb_rule').get_engine()
engine_risk = sql_engine('risk_info', 'risk_info').get_engine()
engine_analysis_new = sql_engine('analysis_new').get_engine()
engine_risk_analysis = sql_engine('risk_analysis').get_engine()

