Python学习笔记-第十二天

** 调用接口生成离线数据 **
# -*- coding: utf-8 -*-
import json
import requests
import sys
import os
abspath = os.path.abspath('.')

reload(sys)
sys.setdefaultencoding("utf-8")


PORSCHE_CENTRE_RANKING_URL = 'http://localhost:10001/test/search'


def generate_json(key, file_name, url, request_json):
    headers = {'content-type': "application/json"}
    resp = requests.post(url, data=json.dumps(request_json), headers=headers)

    if resp.status_code == 200:
        return 'export const ' + key + ':' + resp.text + '\n'
    else:
        print '程序异常,查询条件为:' + json.dumps(request_json)


def generate_data(files_name, api_url):
    # request list order : start_date endDate source channel kpi
    request_list = [('2017-01-01 00:00:00', '2017-03-09 00:00:00'),
                    ('2017-01-01 00:00:00', '2017-03-09 00:00:00'),
                    (0,),
                    (0,),
                    ('prospect2Pc', 'validRate', 'pcVisit', 'prospects',
                     'validProspects', 'sales', 'validProspect2Sales',
                     'prospect2Sales', 'pc2Sales', 'testDriveRate',
                     'validProspect2Pc', 'quickFollowUp')]

    json_data = []
    for start_date in request_list[0]:
        for end_date in request_list[1]:
            for source in request_list[2]:
                for channel in request_list[3]:
                    for kpi in request_list[4]:
                        request_json = {}
                        request_json['startDate'] = start_date
                        request_json['endDate'] = end_date
                        request_json['source'] = source
                        request_json['channel'] = channel
                        request_json['kpi'] = kpi
                        key = wrap_request(
                            start_date, end_date, source, channel, kpi)
                        json_data.append(generate_json(
                            key, files_name, api_url, request_json))
    f = open(files_name, 'w')
    for data in json_data:
        f.writelines(data)
    f.close()


def wrap_request(start_date, end_date, source, channel, kpi):
    return start_date.replace(' ', '-') + '_' + end_date.replace(' ', '-') + '_' + str(source) +\
        '_' + str(channel) + '_' + kpi


if __name__ == '__main__':
    generate_data(abspath + '/porsche_center_ranking.js',
                  PORSCHE_CENTRE_RANKING_URL)

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