无法遍历循环 - python Flask服务器

时间:2015-02-16 20:53:39

标签: python list request

我试图在python中遍历列表对象。我上传了两个文件并通过request.files.getlist("file")电话检索了它。以下是我使用的代码:

修改

def upload_file():
    if request.method == 'POST':
        uploaded_files = request.files.getlist("file")
        print uploaded_files,type(uploaded_files)
        for f in request.files.getlist("file"):
            print request.files.getlist,type(uploaded_files)
            if f and allowed_file(f.filename):
                filename = secure_filename(f.filename)
                f.save(os.path.join('images/', filename))
        return "Success"
    return "Failed to upload"

以下是我为uploaded_files变量获得的输出。

[] <type 'list'>

当我尝试以下行时:

 print request.files.getlist 

我明白了:

<bound method ImmutableMultiDict.getlist of ImmutableMultiDict([('frontCheck',   <FileStorage: u'1_23_f.jpg' ('application/octet-stream')>), ('rearCheck', <FileStorage: u'1_23_r.jpg' ('application/octet-stream')>)])>

它没有按照upload_files中&f; f中的预期迭代列表:&#39;

2 个答案:

答案 0 :(得分:2)

查看help(flask.Request.files)

Each key in :attr:`files` is the name from the
``<input type="file" name="">``

help(werkzeug.datastructures.MultiDict.getlist)

Return the list of items for a given key. If that key is not in the
`MultiDict`, the return value will be an empty list.

所以:你指的是错误的密钥"file";您应该使用"frontCheck""rearCheck"

答案 1 :(得分:-2)

因为你在迭代中返回。一旦达到return语句,函数就会结束。