Python 连接 DataWorks

最近一段时间,对公司在做数据方面的功能做功能性测试。但是作为测试人员,如何快速的去验证数据,让人有点犯难,因为数据量太大,不可能逐条人工核对,就想用 Python 写个脚本,能快速的核对数据的准确性

正所谓:科技的进步就是为了让懒人过的越来越舒服。如果你当前做事的方法让你感觉到了不舒服,那肯定是没找到合适的途径

具体实现:

1、安装依赖


pip install collections
pip install pandas
pip install odps
pip install datetime

2、导包

from collections import defaultdict
import pandas as pd
from datetime import datetime
from odps import ODPS, options

3、访问dataworks 数据库读取数据

class DataWorks:
    def __init__(self):
        # 1、连接配置
        self.options = options
        self.conn = ODPS(
                           access_id='', #登陆账号
                           secret_access_key='', #登陆密码
                           project='project', # odps上的项目名称
                           endpoint='http://service.cn-beijing-xxx:80/api') #官方提供的接口

        # 因dataworks有默认取数条数限制和速度限制,设置以下参数可以取消相关限制
        self.conn.to_global()
        self.options.tunnel.use_instance_tunnel = True
        self.options.tunnel.limit_instance_tunnel = False
        self.options.sql.settings = {'odps.sql.mapper.split.size': 32}

    # 2、读取method
    def exe_sql(self, sql):
        st_time = datetime.now()
        data = []
        with self.conn.execute_sql(sql).open_reader() as reader:
            d = defaultdict(list)  # collection默认一个dict
            # 解析record中的每一个元组,存储方式为(k,v),以k作为key,存储每一列的内容;
            for record in reader:
                for res in record:
                    d[res[0]].append(res[1])
            data = pd.DataFrame.from_dict(d, orient='index').T  # 转换为数据框,并转置,不转置的话是横条数据
        ed_time = datetime.now()
        print('总耗时:', ed_time - st_time)  # 输出sql运行时间,方便sql修改、维护
        return data

    def create_sql(self, table_name):
        # 3、读数sql
        get_data_sql = f""" 
                       select * from {table_name} WHERE pt = '20220820';
        """
        return get_data_sql


if __name__ == '__main__':
    obj = DataWorks()
    get_data_sql = obj.create_sql("xx")
    # 4、获取数据
    df = obj.exe_sql(get_data_sql)
    print(df)

猜你喜欢

转载自blog.csdn.net/Jiazengzeng/article/details/127212550