# coding=utf-8
__author__ = 'fang'
import logging
import datetime
import MySQLdb
import MySQLdb.cursors as mc
import settings
import redis
# from res import settings
Cursor = mc.Cursor


#配置日志
def config_log():
    import os, sys
    log_path = os.path.join(os.path.dirname(__file__), '../log')
    single_log_path = os.path.join(log_path, datetime.datetime.now().strftime('%Y-%m-%d'))
    if not os.path.exists(single_log_path):
        os.makedirs(single_log_path)

    log_file_path = os.path.join(single_log_path, str(datetime.datetime.now())+'.txt')

    root = logging.getLogger()
    printf = logging.StreamHandler()
    filef = logging.FileHandler(log_file_path)
    printf.setLevel(logging.DEBUG)
    filef.setLevel(logging.DEBUG)
    printf.setFormatter(logging.Formatter('%(asctime)s --%(message)s'))
    filef.setFormatter(logging.Formatter('%(asctime)s --%(message)s'))
    root.addHandler(printf)
    root.addHandler(filef)
    return root


#日志装饰器
def addlog(fn):

    #装饰器方法
    def call():
        try:
            res = fn()
        except Exception, e:
            log = config_log()
            log.error('error:%s: %s' %(fn.__name__, e))
            return
        return fn
    return call


class Sql(object):
    def __init__(self,
                 cursorclass = Cursor,
                 host = settings.HOST,
                 user = settings.USER,
                 passwd = settings.PASSWORD,
                 dbname = settings.DATABASE,
                 dirver = MySQLdb,
                 ):
        self.cursorclass = cursorclass
        self.host = host
        self.user = user
        self.passwd = passwd,
        self.dbname = dbname
        self.dirver = dirver
        self.connection = self.dirver.connect(
            host = host,        # 非 self.host
            user = user,
            passwd = passwd,
            db = dbname,
            charset='utf8',     # 这一步十分重要，否则插入utf8格式出错，即使数据库设置该字符集
            cursorclass = cursorclass,
        )

        self.cursor = self.connection.cursor()

    def __iter__(self):
        for item in self.cursor:
            yield item

    def __enter__(self):
        # 返回游标对象
        return self.cursor


    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connection.commit()
        self.cursor.close()                 # 关闭游标
        if isinstance(exc_val, Exception):
            log = config_log()
            log.error('error:%s: %s' %(exc_val, 'mysql'))
            self.connection.rollback()      # 回滚

        else:
            self.connection.commit()        # 执行写入

        self.connection.close()             # 关闭连接






class Mysql(object):
    def __init__(self, sql, type=0,column=None, *args, **kwargs):
        self.sql = sql
        self.type = type
        self.column = column

    @property
    def run(self):
        with Sql() as cur:
            cur.execute(self.sql)
            if self.type != 2:
                return self.getValue(cur.fetchall() if not self.type else cur.fetchone(), self.type, self.column)

    def getValue(self, values, type_, column):
        if values and column:
            if type_ == 1:
                return dict(zip(column, values))
            else:
                lis = []
                for i in values:
                    lis.append(dict(zip(column, i)))
                return lis


mysql = Mysql

#redis
class Redis(object):
    def __init__(self):

        self.con = redis.StrictRedis(host=settings.REDIS_HOST, port=settings.REDIS_PORT)




#etc..

if __name__ == '__main__':
    # print mysql('update user set id=1 where id=5').run
    column = ('id', 'username')
    print mysql('select %s,%s from user;' %column, column=column).run
