美文网首页我爱编程
python 生成csv 并压缩成zip 上传阿里 oss

python 生成csv 并压缩成zip 上传阿里 oss

作者: 星丶雲 | 来源:发表于2018-05-07 16:55 被阅读0次

    import zipfile, csv, os, shutil

    import oss2

    def zip_ya(startdir, file_news):

    # startdir = "./media"  # 要压缩的文件夹路径

        # file_news = "MMC_" + str(datetime.now()) + ".zip"  # 压缩后文件夹的名字

        z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)# 参数一:文件夹名

        for dirpath, dirnames, filenamesin os.walk(startdir):

    fpath = dirpath.replace(startdir, '')# 这一句很重要,不replace的话,就从根目录开始复制

            fpath = fpathand fpath + os.sepor ''  # 这句话理解我也点郁闷,实现当前文件夹以及包含的所有文件的压缩

            for filenamein filenames:

    z.write(os.path.join(dirpath, filename), fpath + filename)

    print u'压缩成功'

    # import pandas as pd

    @csrf_exempt

    def to_excel(request):

    if request.method =='POST':

    json_data = json.loads(request.body)

    else:

    return HttpResponseBadRequest('Bad Request')

    if "order_ids" in json_data:

    id_list = json_data["order_ids"]

    else:

    return JsonResponse({"result":1, "message":"ids is required"})

    for orderin id_list:

    temps = IotTemp.objects.filter(order=order).order_by('time') \

    .values("time", "temperature").distinct()

    file_name = order.mac + order.number + datetime.now().strftime("%Y-%m-%d-%H-%M-%S") +".csv"

            with open(os.path.join(sys.path[0], "iot", "media", file_name), 'wb')as csvfile:

    writer = csv.writer(csvfile, dialect='excel')

    writer.writerow(["ZenMeasureID:", order.mac, "Tracking No.:", order.number])

    writer.writerow(["Date", "Time", "Temperature(C)"])

    for iin temps:

    writer.writerow(["%s", "%s", "%s"]) % (

    i.time.strftime("%Y-%m-%d"), i.time.strftime("%H:%M:%S"), i.temperature)

    startdir ="/media"  # 要压缩的文件夹路径

            file_news ="MMC_" + datetime.now().strftime("%Y-%m-%d-%H-%M-%S") +".zip"

            zip_ya(startdir, file_news)

    # user_sts_key() 连接 上传oss

            AccessKeyID =""

            AccessKeySecret =""

            auth = oss2.Auth(AccessKeyID, AccessKeySecret)

    bucket = oss2.Bucket(auth, 'http://oss-cn-beijing.aliyuncs.com', 'iot-server')

    result = bucket.put_object('../media/file_news', 'iot-server/records/',

                                      headers={'Content-Type':'application/json; charset=utf-8',

                                                'Accept-Encoding':'gzip'})

    if result.status =='200':

    #  删除

                shutil.rmtree("../media")

    os.remove(file_news)

    data = {

    "url":"http://" +'iot-server/records/' +"oss-cn-beijing.aliyuncs.com/" +"%s" % (file_news)

    }

    return JsonResponse({"result":0, "message":"success", "data": data})

    else:

    return JsonResponse({"result":1, "message":"failed"})

    https://help.aliyun.com/document_detail/32030.html

    相关文章

      网友评论

        本文标题:python 生成csv 并压缩成zip 上传阿里 oss

        本文链接:https://www.haomeiwen.com/subject/lijvrftx.html