Python學(xué)習(xí)筆記-第十二天

** 調(diào)用接口生成離線數(shù)據(jù) **
# -*- 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)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容