python django动态压缩和下载

时间:2012-06-12 02:48:59

标签: python html django

我有一个复选框表单。我试图这样做,如果用户检查“视频”框并提交表单,然后视频文件被压缩,django生成一个弹出用户屏幕上的动态下载。我希望音频发生同样的事情。但是,如果用户同时选择复选框和提交,则音频和视频文件以压缩形式组合,并为用户弹出下载。我不希望任何存储在磁盘上,所以我使用StringIO。没有下载弹出窗口

HTML

<form>
<input type="checkbox" name="list" value="audio"/> Audio<br />
<input type="checkbox" name="list" value="video"/> Video<br />
<input type="submit" value="submit" /> 
</form>

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cgitb; cgitb.enable()
import cgi
from zipfile import ZipFile
from StringIO import StringIO
from django.http import HttpResponse
from django.core.servers.basehttp import FileWrapper
files = 0
def zip (content):
    buffer= StringIO.StringIO()
    z= zipfile.ZipFile( buffer, "w" )
    z.writestr(content)
    z.close()
    # generate the file
    response = HttpResponse(FileWrapper(z), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=z.zip'
    return response
form = cgi.FieldStorage()
mylist = form.getlist('list')
print 'Content-Type: text/plain\n'
for item in mylist:
  if item == 'video':
    files = '../download/video.html'
    zip(files)
  elif item == 'audio':
    files = '../download/audio.html'
    zip(files)
  elif item == 'audio' and 'video':
    files = '../download/audio.html'+'../download/video.html'
    zip(files)
  else:
    print 'nothing selected'

1 个答案:

答案 0 :(得分:1)

为了确保for循环不能正常工作,最后一个elif中的第三个代码将永远不会执行,因为它与第二个相同 item == 'audio' and 'video'item == 'audio and True'相同,与item == 'audio'

相同

我会改变循环代码看起来更简单

files = []
for item in mylist:
  if item == 'video':
    files.append('../download/video.html')
  elif item == 'audio':
    files.append('../download/audio.html')
zip(files)

然后重新锁定zip以处理文件列表

def zip (filenames):
    buffer= StringIO.StringIO()
    z= zipfile.ZipFile( buffer, "w" )
    [z.writestr(f) for f in filenames]
    z.close()
    # generate the file
    response = HttpResponse(FileWrapper(z), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename=z.zip'
    return response

您还必须确保视图函数返回zip函数返回的内容。