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

2024-06-17 15:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

为了测试一个Flask应用程序,我收到了一个Flask测试客户端的请求,该请求以文件作为附件

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)

处理上述POST请求的Flask服务器端点代码如下

@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()

我得到这个输出

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

Upload Files:
[]

如果我改变

scc.data['file'] = (open(file_path, 'rb'),file_name)

into(认为它可以处理多个文件)

scc.data['file'] = [(open(file_path, 'rb'),file_name),(open(file_path, 'rb'),file_name1)]

我仍然得到类似的输出:

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

Upload Files:
[]

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

注:

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

谢谢

已经引用了这些链接:

Flask and Werkzeug: Testing a post request with custom headers

Python - What type is flask.request.files.stream supposed to be?


Tags: pathnameclientflaskdatarequesttypeservice