如何使用 Flask test_client 将多个文件上传到一个 API 端点?
我正在尝试使用 Flask test_client 将多个文件上传到一个 Web 服务,该服务接受多个文件并将它们组合成一个大文件。
我的 Controller 如下所示:
@app.route("/combine/file", methods=["POST"])
@flask_login.login_required
def combine_files():
user = flask_login.current_user
combined_file_name = request.form.get("file_name")
# Store file locally
file_infos = []
for file_data in request.files.getlist('file[]'):
# Get the content of the file
file_temp_path="/tmp/{}-request.csv".format(file_id)
file_data.save(file_temp_path)
# Create a namedtuple with information about the file
FileInfo = namedtuple("FileInfo", ["id", "name", "path"])
file_infos.append(
FileInfo(
id=file_id,
name=file_data.filename,
path=file_temp_path
)
)
...
我的测试代码如下所示:
def test_combine_file(get_project_files):
project = get_project_files["project"]
r = web_client.post(
"/combine/file",
content_type='multipart/form-data',
buffered=True,
follow_redirects=True,
data={
"project_id": project.project_id,
"file_name": "API Test Combined File",
"file": [
(open("data/CC-Th0-MolsPerCell.csv", "rb"), "CC-Th0-MolsPerCell.csv"),
(open("data/CC-Th1-MolsPerCell.csv", "rb"), "CC-Th1-MolsPerCell.csv")
]})
response_data = json.loads(r.data)
assert "status" in response_data
assert response_data["status"] == "OK"
但是,我无法让 test_client 实际上传这两个文件。如果指定了多个文件,则 API 代码循环时 file_data 为空。我已经尝试过我自己的 ImmutableDict 与两个"file"条目,一个文件元组列表,一个文件元组元组,任何我能想到的东西。
在 Flask test_client 中指定多个文件上传的 API 是什么?我在网上找不到这个! :(
最佳答案
测试客户端获取文件对象列表(由 open()
返回),因此这是我使用的测试实用程序:
def multi_file_upload(test_client, src_file_paths, dest_folder):
files = []
try:
files = [open(fpath, 'rb') for fpath in src_file_paths]
return test_client.post('/api/upload/', data={
'files': files,
'dest': dest_folder
})
finally:
for fp in files:
fp.close()
我认为如果您丢失了元组(但保留 open()
),那么您的代码可能会工作。
关于python - 如何使用 Flask test_client 上传多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47216204/