Validate and save a ZIP file in Flask
<p>I'm writing an app using Flask and one of the things I want in it is the ability to upload a ZIP that conforms to a specific form; as such I have a small function that takes a <code>FileStorage</code> object from the form and first unzips it, checks the contents, and then tries to save. There's a problem, however - apparently unzipping it "breaks" the <code>FileStorage</code> object, as the following function:</p>

<pre class="lang-py prettyprint-override"><code>def upload_modfile(modfile):
    if not modfile.filename.endswith('.zip'):
        raise ModError('Incorrect filename')
    mod_path = join(get_mods_path(), secure_filename(modfile.filename))
    if isfile(mod_path):
        raise ModError('File ' + modfile.filename + ' already exists')
    modzip = ZipFile(modfile)
    base_filename = modfile.filename[:-4]
    modzip_contents = modzip.namelist()
    if join(base_filename, 'info.json') not in modzip_contents:
        raise ModError('Could not validate file')
    modfile.save(mod_path)
    return True
</code></pre>

<p>saves <code>modfile</code> as a text file saying <code>Archive: &lt;filename&gt;.zip</code>. If I comment out the entire <code>ZipFile</code> bit (i.e. everything involving <code>modzip</code>), the file is saved just fine.</p>

<p>I'm pretty much brand new to Python and am a little confused as to what to do in this case, save for saving the file in <code>/tmp</code>. Should I somehow clone <code>modfile</code> by way of some stream? Is there a way of "rewinding" the stream pointer within <code>FileStorage</code> that I'm missing?</p>