如何在Python中创建密码保护的CSV或ZIP存档

lmvvr0a8  于 2023-11-14  发布在  Python
关注(0)|答案(1)|浏览(114)
async def get_report(id):
    try:
        data = await collection.find({"_id": ObjectId(id)}).to_list(None)
        if data:
            df1 = pd.DataFrame(data)
            directory = Path("/")
            file_name = "abcd.csv"
            file_path = directory / file_name
            df1.to_csv(file_path, index=False)
            password = "1234"
            zip_file_path = directory / (file_name + ".zip")
            with zipfile.ZipFile(zip_file_path, 'w', zipfile.ZIP_DEFLATED) as zf:
                zf.setpassword(password.encode('utf-8'))
                zf.write(file_path, arcname=file_name)
            response = FileResponse(zip_file_path, media_type='application/zip', filename=file_name+".zip")
            return response
            #json_data = {'file':str(zip_file_path)}
            #response = requests.post(url,json=json_data)
    except Exception as e:
        print(e)

字符串
这是我的代码,在这里我试图创建 Dataframe 的CSV和发送文件在电子邮件(代码不在这里,但CSV是在邮件发送(其工作))文件正在下载CSV和ZIP两者.但不是密码保护(返回响应)在这里,是可能的,如果是的,我在这里缺少什么.

euoag5mw

euoag5mw1#

内置的zipfile模块不支持写密码加密的文件(只支持阅读)参见[docs][1]你可以使用pyminizip:

pip install pyminizip
import pyminizip

async def get_report(id):
    try:
        data = await collection.find({"_id": ObjectId(id)}).to_list(None)
        if data:
            df1 = pd.DataFrame(data)
            directory = Path("/")
            file_name = "abcd.csv"
            file_path = directory / file_name
            df1.to_csv(file_path, index=False)# remove if you dont want to save .csv file as well
            password = "1234"
            zip_file_path = directory / (file_name. + ".zip")
            pyminizip.compress(file_path, None, zip_file_path, password, 0)
            response = FileResponse(zip_file_path, media_type='application/zip', filename=file_name+".zip")
            return response
            #json_data = {'file':str(zip_file_path)}
            #response = requests.post(url,json=json_data)
    except Exception as e:
        print(e)

  [1]: https://docs.python.org/3/library/zipfile.html#zipfile.ZipFile.setpassword

相关问题