如何使用Flask测试客户端发布多个文件?

use*_*183 9 python post werkzeug flask

为了测试Flask应用程序,我得到了一个烧瓶测试客户端POST请求,文件作为附件

def make_tst_client_service_call1(service_path, method, **kwargs):
    _content_type = kwargs.get('content-type','multipart/form-data')
    with app.test_client() as client:
        return client.open(service_path, method=method,
                           content_type=_content_type, buffered=True,               
                                             follow_redirects=True,**kwargs)

def _publish_a_model(model_name, pom_env):
    service_url = u'/publish/'
    scc.data['modelname'] = model_name
    scc.data['username'] = "BDD Script"
    scc.data['instance'] = "BDD Stub Simulation"
    scc.data['timestamp'] = datetime.now().strftime('%d-%m-%YT%H:%M')
    scc.data['file'] = (open(file_path, 'rb'),file_name)
    scc.response = make_tst_client_service_call1(service_url, method, data=scc.data)
Run Code Online (Sandbox Code Playgroud)

处理上述POST请求的Flask Server端点代码是这样的

@app.route("/publish/", methods=['GET', 'POST'])
def publish():
    if request.method == 'POST':
        LOG.debug("Publish POST Service is called...")
        upload_files = request.files.getlist("file[]")
        print "Files :\n",request.files
        print "Upload Files:\n",upload_files
        return render_response_template()
Run Code Online (Sandbox Code Playgroud)

我得到了这个输出

Files:
ImmutableMultiDict([('file', <FileStorage: u'Single_XML.xml' ('application/xml')>)])

Upload Files:
[]
Run Code Online (Sandbox Code Playgroud)

如果我改变

scc.data['file'] = (open(file_path, 'rb'),file_name)
Run Code Online (Sandbox Code Playgroud)

进(认为它会处理多个文件)

scc.data['file'] = [(open(file_path, 'rb'),file_name),(open(file_path, 'rb'),file_name1)]
Run Code Online (Sandbox Code Playgroud)

我仍然得到类似的输出:

Files:
ImmutableMultiDict([('file', <FileStorage: u'Single_XML.xml' ('application/xml')>), ('file', <FileStorage: u'Second_XML.xml' ('application/xml')>)])

Upload Files:
[]
Run Code Online (Sandbox Code Playgroud)

问题:为什么request.files.getlist("file []")返回一个空列表?如何使用flask测试客户端发布多个文件,以便可以 在flask服务器端使用request.files.getlist("file []")检索它?

注意:

  • 我想有烧瓶客户端我不想要卷曲或任何其他基于客户端的解决方案.
  • 我不想在多个请求中发布单个文件

谢谢

已经提到这些链接:

Flask和Werkzeug:使用自定义标头测试发布请求

Python - flask.request.files.stream应该是什么类型的?

Luk*_*ský 7

您将文件作为参数命名发送file,因此您无法使用名称查找它们file[].如果要获取名为file列表的所有文件,则应使用以下命令:

upload_files = request.files.getlist("file")
Run Code Online (Sandbox Code Playgroud)

另一方面,如果你真的想从中读取它们file[],那么你需要像这样发送它们:

scc.data['file[]'] = # ...
Run Code Online (Sandbox Code Playgroud)

(file[]语法来自PHP,它仅在客户端使用.当您将名称相同的参数发送到服务器时,您仍然可以使用它来访问它们$_FILES['file'].)