其他分享
首页 > 其他分享> > 接口数据写入CSV

接口数据写入CSV

作者:互联网

# api_util.py

import requests


class SendRequest:
    sess = requests.session()

    def all_send_request(self, method, url, **kwargs):
        print('\n----接口测试开始----')
        # print('\n----请求url:%s----'%url)
        # print('\n----**kwargs:%s----'%kwargs)
        res = SendRequest.sess.request(method, url, **kwargs)
        print('\n----接口测试结束----')
        return res

    def login_system(self):
        method = 'post'
        url = 'http://127.0.0.1:80/api/mgr/signin'
        data = {
            'username': 'byhy',
            'password': '88888888'
        }
        try:
            res = SendRequest().all_send_request(method, url, data=data)
        except BaseException as e:
            print('\n****登录系统失败****')
        else:
            print('\n****登录系统成功****')
        # return res

# test_writecsv.py

import csv
import json
import time

from common.api_util import SendRequest


class TestApi:
    # 前置步骤
    def setup(self):
        print('\n****执行前置步骤:登录系统****')
        SendRequest().login_system()

    # 用例
    def test_customer_list(self):
        method = 'get'
        url = 'http://127.0.0.1:80/api/mgr/customers'
        params = {
            'action': 'list_customer',
            'pagesize': 100,
            'pagenum': 1,
            'keywords': ''
        }
        res = SendRequest().all_send_request(method, url, params=params)
        print(res.json())
        assert res.status_code == 200
        # 结果写入csv文件
        # 文件地址与名称
        filepath = f'customerlist_{time.strftime("%Y%m%d%H%M%S",time.localtime())}.csv'
        header = ["id", "name", "phonenumber", "address"]
        header = []
        #  获取表头
        dict1 = res.json()['retlist'][0]

        for key in dict1.keys():
            header.append(key)
        # print(header)
        # 获取数据列表
        rows = res.json()['retlist']
        with open(filepath, 'w', newline='', encoding='utf-8') as f:
            f_csv = csv.DictWriter(f, fieldnames=header)
            f_csv.writeheader() # 写入header
            f_csv.writerows(rows) # 写入列表数据

        return res

结果:

 

 

 

 

 

 

 

 

标签:csv,url,res,写入,接口,----,print,SendRequest,CSV
来源: https://www.cnblogs.com/Avicii2018/p/16660054.html