循环迭代失败 - python Flask 服务器
Fails to iterate through a loop - python Flask server
我正在尝试遍历 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')>)])>
它没有像 'f in uploaded_files:'
中预期的那样遍历列表
因为你return在迭代里面。一旦到达 return 语句,函数就会结束。
正在查看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"
.
我正在尝试遍历 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')>)])>
它没有像 'f in uploaded_files:'
中预期的那样遍历列表因为你return在迭代里面。一旦到达 return 语句,函数就会结束。
正在查看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"
.