# -*- coding: utf-8 -*- # !/usr/bin/env python import csv import datetime import getopt import os import sys import requests PROJECT_ROOT = os.path.join(os.path.abspath(os.path.split(os.path.realpath(__file__))[0] + "/.."), '..') sys.path.insert(0, PROJECT_ROOT) from script.base import init_env os.environ["DJANGO_SETTINGS_MODULE"] = "configs.production_local" init_env(False) from apps.web.merchant.utils import JDMerchant from django.conf import settings def download_bill_file(merchantNo, start, end): st = datetime.datetime.strptime(start, "%Y-%m-%d") if end: et = datetime.datetime.strptime(end, "%Y-%m-%d") else: et = datetime.datetime.now() _dirPath = os.path.join(settings.PROJECT_ROOT, "script/jdBill/{}".format(merchantNo)) if not os.path.exists(_dirPath): os.makedirs(_dirPath) while True: if (et - st).days == 0: break billDate = st.strftime("%Y%m%d") st = st + datetime.timedelta(days=1) try: _downloadPath = JDMerchant.query_bill_file(merchantNo, billDate=billDate) except Exception as e: print "{} {}".format(billDate, e) continue response = requests.get(url=_downloadPath) content = response.content with open(os.path.join(_dirPath, "bill_{}.zip".format(billDate)), "wb") as f: f.write(content) def download_settle_file(merchantNo, start, end): dataRows = list() st = datetime.datetime.strptime(start, "%Y-%m-%d") if end: et = datetime.datetime.strptime(end, "%Y-%m-%d") else: et = datetime.datetime.now() _dirPath = os.path.join(settings.PROJECT_ROOT, "script/jdSettle/{}".format(merchantNo)) if not os.path.exists(_dirPath): os.makedirs(_dirPath) days = (et - st).days for _index in range(days): _date = st + datetime.timedelta(_index) _dateStr = _date.strftime("%Y-%m-%d") _settleDataList = list() result = JDMerchant.query_settle( agentNo="112122276", startTime=_dateStr, endTime=_dateStr, merchantNo=merchantNo, ) if "dataList" not in result or not result["dataList"]: continue _settleData = result["dataList"][0] dataRows.append(_settleData) with open(os.path.join(_dirPath, "settle.csv"), "w") as f: wr = csv.DictWriter(f, fieldnames=[ "settleDate", "merchantNo", "merchantName", "settleType", "settlementAmount", "settleAccountNo", "orderStatus", "remark" ]) wr.writeheader() wr.writerows(dataRows) if __name__ == '__main__': try: options, args = getopt.getopt(sys.argv[1:], 's:e:m:', ['start=', 'end=', 'merchantNo=']) except getopt.GetoptError as e: print(str(e)) sys.exit() start = None end = None merchantNo = None for name, value in options: if name in ('-s', '--start'): start = value if name in ('-e', '--end'): end = value if name in ('-m', '--merchantNo'): merchantNo = str(value) print 'start = {}'.format(start) print 'end = {}'.format(end) print 'merchant no = {}'.format(merchantNo) download_bill_file(merchantNo, start, end) download_settle_file(merchantNo, start, end)