google app engine download a file containing files

2019-08-21 11:14发布

Okay, I have:

class Content(db.Model):
    code=db.TextProperty()

And there are 3 different values of code stored in the database. How would I create a zip file that stores the three values of code in 3 separate files that would be downloaded?

Based on eric.f's answer: I rewrote his code to make it to do what I wanted:

    contents = db.GqlQuery("SELECT * FROM Content ORDER BY created DESC")
    output = StringIO.StringIO()
    with zipfile.ZipFile(output, 'w') as myzip:
        for content in contents:
            if content.code:
                code=content.code
            else:
                code=content.code2
            myzip.writestr('udacity_code'+`content.key().id()`, code)
    self.response.headers["Content-Type"] = "application/zip"
    self.response.headers['Content-Disposition'] = "attachment; filename=test.zip"
    self.response.out.write(output.getvalue())

I got an error though...

self.response.out.write(output.getvalue(), "utf-8")
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/StringIO.py", line 270, in getvalue
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb4 in position 10: ordinal not in range(128)

1条回答
Viruses.
2楼-- · 2019-08-21 11:36
import zipfile
import StringIO

output = StringIO.StringIO()

with zipfile.ZipFile(output, 'w') as myzip:
    myzip.writestr('file1.txt', 'aaaaaaaaa')
    myzip.writestr('file2.txt', 'bbbbbbbbb')
    myzip.writestr('file3.txt', 'ccccccccc')

then make your response, set output.getvalue() as the content, and set headers as below:

Content-type: application/zip
Content-disposition: attachment; filename=test.zip
查看更多
登录 后发表回答