Python学习笔记-第十天

经常看到测试的同学核对指标的时候一个sql一个sql去执行,然后去核对值,感觉浪费了太多时间,今天写了一个Python程序将这部分工作自动化起来了。

** config **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

' this is a config module'

__author__ = 'wenbo chen'

import ConfigParser
import sys
reload(sys)
sys.setdefaultencoding('utf8')


CONFIG = '/Users/apple/code/python/python_fetch_data/config.ini'


# 读取配置文件
def read_config(namespace, key):
    config = ConfigParser.ConfigParser()
    config.read(CONFIG)
    return config.get(namespace, key)


# 读取配置文件
def read_sql_config(file_name, parameter):
    with open(file_name, 'r') as f:
        sql = reduce(lambda x, y: x.strip() + ' ' + y.strip(), f.readlines())
        if '#startDate' in sql:
            sql = sql.replace('#startDate', '\'' + parameter[0] + '\'')
        if '#endDate' in sql:
            sql = sql.replace('#endDate', '\'' + parameter[1] + '\'')
        if '#source_id' in sql:
            sql = sql.replace('#source_id', parameter[2])
        if '#channel_id' in sql:
            sql = sql.replace('#channel_id', parameter[3])
        if '#dealer_id' in sql:
            sql = sql.replace('#dealer_id', parameter[4])
    return sql


if __name__ == '__main__':
    print read_config('database', 'user')
** database **
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os
reload(sys)
sys.setdefaultencoding('utf8')
abspath = os.path.abspath('.') + '/python_fetch_data/config'
sys.path.append(abspath)
from config import config
import MySQLdb as mysqldb


# 查询sql的值
def query_data(kpi_sql):
    db = mysqldb.connect(host=config.read_config('database', 'host'),
                         user=config.read_config('database', 'user'),
                         passwd=config.read_config('database', 'passwd'),
                         db=config.read_config('database', 'db'))
    cursor = db.cursor()
    cursor.execute(kpi_sql)
    # 搜取所有结果
    results = cursor.fetchone()
    db.close()
    return results
···

你可能感兴趣的:(Python学习笔记-第十天)