eqImageDeal.py 4.53 KB
import logging
import pandas as pdas
import os
import chardet
import math
import requests
from urllib.parse import urlparse
from roputil import RopUtils

print("sys config " + __name__)
log_name = './log/imageequity/equityimagedeal.log'
log_format = '[%(asctime)s-%(filename)s-%(levelname)s:%(message)s]'
log_level = logging.DEBUG
log_mode = 'a'
logging.basicConfig(filename=log_name, format=log_format, level=log_level, filemode=log_mode, encoding='utf-8')

class equityImageDeal:
    def __init__(self):
        logging.info("init construct bean")

    # 获取文件名,从URL的路径中提取
    def getFileNameFromUrl(self, fileUrl):
        url_path = urlparse(fileUrl).path
        file_name = os.path.basename(url_path)
        return file_name

    def ospathinit(self, filePath):
        # 使用 os.path.exists() 函数检查文件夹是否存在
        if not os.path.exists(filePath):
            # 如果文件夹不存在,创建它
            os.makedirs(filePath)
            print(f"文件夹 {filePath} 创建成功")
        else:
            print(f"文件夹 {filePath} 已存在")

    def downloadImageFile(self, fileUrl, fileName):
        # 发送HTTP GET请求获取文件内容
        response = requests.get(fileUrl)
        # 检查响应状态码是否为200,表示请求成功
        if response.status_code == 200:
            # 以二进制写入模式打开本地文件,然后写入响应内容
            with open(fileName, "wb") as local_file:
                local_file.write(response.content)
                
            print(f"文件已下载到 {fileName}")
        else:
            print("下载失败,状态码:", response.status_code)

    def dealImageData(self, excelFilePath, exportPath):
        logging.info('excelFile:%s, exportPath:%s' %(excelFilePath, exportPath))
        # 1. 读取文件内容
        eqDataFrames = pdas.read_excel(excelFilePath)
        for drow in eqDataFrames.itertuples():
            # 购车发票地址	合同购买时里程数地址	行驶证主页地址	行驶证副页地址	其他资料地址
            buyCarListUrl = drow.购车发票地址
            buyCarMileageUrl = drow.合同购买时里程数地址
            carCheckMainUrl = drow.行驶证主页地址
            carCheckCommonUrl = drow.行驶证副页地址
            carOtherUrlList = []

            # 2. 初始化文件路径
            currentFileExportPath = f'{exportPath}{drow.车架号}_{drow.合同号}'
            self.ospathinit(currentFileExportPath)
            
            # 3. 执行导出
            if (drow.其他资料地址 is not None and pdas.isna(drow.其他资料地址) is False):
                carOtherUrlList = drow.其他资料地址.split(',')
                i = 1
                for itemUrl in carOtherUrlList:
                    fileName = f'{currentFileExportPath}/其他-{i}-{self.getFileNameFromUrl(itemUrl)}'
                    self.downloadImageFile(itemUrl, fileName)
                    i+=1
            if (buyCarListUrl is not None and pdas.isna(buyCarListUrl) is False):
                fileName = f'{currentFileExportPath}/购车发票地址-{self.getFileNameFromUrl(buyCarListUrl)}'
                self.downloadImageFile(buyCarListUrl, fileName)
            if (buyCarMileageUrl is not None and pdas.isna(buyCarMileageUrl) is False):
                fileName = f'{currentFileExportPath}/合同购买时里程数地址-{self.getFileNameFromUrl(buyCarMileageUrl)}'
                self.downloadImageFile(buyCarMileageUrl, fileName)
            if (carCheckMainUrl is not None and pdas.isna(carCheckMainUrl) is False):
                fileName = f'{currentFileExportPath}/行驶证主页地址-{self.getFileNameFromUrl(carCheckMainUrl)}'
                self.downloadImageFile(carCheckMainUrl, fileName)
            if (carCheckCommonUrl is not None and pdas.isna(carCheckCommonUrl) is False):
                fileName = f'{currentFileExportPath}/行驶证副页地址-{self.getFileNameFromUrl(carCheckCommonUrl)}'
                self.downloadImageFile(carCheckCommonUrl, fileName)

            # 打印日志
            # print(buyCarListUrl, buyCarMileageUrl, carCheckMainUrl, carCheckCommonUrl, carOtherUrlList)


if __name__ == "__main__":
    print('start deal equity image.')
    eqImageDeal = equityImageDeal()

    dealMonth = '202309'
    fileName = '无忧权益订单数据20230915142850.xlsx'

    excelFilePath = f'F:/eq/{dealMonth}/{fileName}'
    exportPath = f'F:/eq/{dealMonth}/export/'

    dealRes = eqImageDeal.dealImageData(excelFilePath, exportPath)
    print('deal result:', dealRes)