1.缘起
工作中,我们有时需要测试web post功能是否正常。这类测试,客户端的请求很容易实现,比如portman,比如非常简单的命令行curl语法:
curl -X POST http://127.0.0.1:5000/post-endpoint/ -F "warning_image=@/path/to/your/file"
客户端的请求测试,我没有找到好的测试工具。现在,我一般会使用flask直接在嵌入式平台上搭建测试环境。
2.一个支持http post 文件保存的最简例程
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 获取当前脚本文件所在目录的父目录,并构建相对路径
import os
import sys
current_dir = os.path.dirname(os.path.abspath(__file__))
project_path = os.path.join(current_dir, '..')
sys.path.append(project_path)
sys.path.append(current_dir)
from flask import Flask, request, jsonify
app = Flask(__name__)
UPLOAD_FOLDER = '/tmp'
@app.route('/post-endpoint1/', methods=['POST'])
def post_endpoint():
# 获取 POST 请求的 JSON 数据
#data = request.get_json()
#print('Received POST data:', data)
if 'warning_image_file' not in request.files:
return jsonify({"error": "No file part"}), 400
file = request.files['warning_image_file']
if file.filename == '':
return jsonify({"error": "No selected file"}), 400
# 保存文件
file_path = os.path.join(UPLOAD_FOLDER, file.filename)
file.save(file_path)
print(f'File saved to {file_path}')
# 返回成功响应
return jsonify({"message": "File uploaded successfully", "file_path": file_path})
if __name__ == '__main__':
app.run(debug=True)
注意:
- 上传路径使用了/tmp避免权限问题
- 上面的代码仅处理了post 上来的文件保存。
- flask默认只能提供127.0.0.1的侦听权限,对于测试而言这足够了。
附录A flask的安装
pip install flask --timeout 200 -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com