python corrupt extra field_Python生成的zipfile已损坏

我有一个类似下面的Flask视图,它生成几个CSV文件,并将它们放入一个zip归档文件中以发送给用户。在@route('/download/')

def download(self, some_value):

"""Return a ZIP archive with several CSVs in"""

# ensure the thing exists

at = (MyModel.SomeModel

.query

.filter((MyModel.SomeModel

.some_primary_key) == some_value)

.first_or_404())

# what queries do we need to run?

queries = cascade_export(at)

# prepare a zip

out = BytesIO()

with zipfile.ZipFile(out, 'w') as zf:

# run each query

for tn, q in queries.items():

# make the query

conn = db.engine.connect()

r = conn.execute(q.query, **q.params)

conn.close()

# map the col names

cols = [c.name for c in r.cursor.description]

col_map = {

c.name: c.key

for c in q.model.__table__.columns

}

col_order = [col_map[c] for c in cols]

# put it into a csv in memory

f = StringIO()

writer = csv.DictWriter(f, fieldnames=col_order)

for row in r:

writer.writerow({

k: v

for k, v in zip(col_order, row)

})

# write it into the zip

f.seek(0)

zf.writestr('{0}.csv'.format(q.model.__name__), f.read())

out.seek(0)

fn = 'export-{0}-{1}.zip'.format(

at.some_name,

datetime.datetime.now().strftime('%d-%m-%Y-%H-%M-%S')

)

return send_file(out,

attachment_filename=fn,

as_attachment=True,

cache_timeout=0)

在我的测试中,r是一个响应对象,以下两个过程都通过:

^{pr2}$

但是,当我尝试在ubuntu中打开该文件时,我得到了以下结果:Archive: ../downloads/export-Something-20-04-2018-11-59-04.zip

warning [../downloads/export-Something-20-04-2018-11-59-04.zip]: 300 extra bytes at beginning or within zipfile

(attempting to process anyway)

error [../downloads/export-Something-20-04-2018-11-59-04.zip]: start of central directory not found;

zipfile corrupt.

(please check that you have transferred or created the zipfile in the

appropriate BINARY mode and that you have compiled UnZip properly)

如有任何想法/帮助,不胜感激。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值