Situation description:
@app.route('/auth/audio/save', methods=['POST'])
def save_audio():
# files = request.files
resp_dict = {'message': "success"}
file = request.files.get("file")
if file.filename == "":
resp_dict['message'] = "[No file] file.filename == ''"
return jsonify(resp_dict), 400
# data = request.get_json()
data = request.form
logger.info(f"data: {data}")
check_required_params(data, ['user_id'])
user_id = data["user_id"]
audio_dir = os.path.join(app_dir, 'db_files/audio')
save_path = os.path.join(audio_dir, f'{user_id}.bin')
file.save(save_path)
return jsonify(resp_dict), 200
I have a Flask view function which handles POST request that sends a file and data wrapped inside the request body.
The send request codes show below:
def test_send_audio():
cur_dir = os.path.dirname(os.path.abspath(__file__))
audiopath = os.path.join(cur_dir, "test.wav")
files = {'file': open(audiopath, 'rb')}
data = {"user_id": 2}
# headers = {
# "Content-Type": "multipart/form-data",
# }
# NOTE: Not sure why handlers can't get files when I add headers
response = requests.post(
save_audio_url,
# headers=headers,
files=files,
data=data,
)
My question:
- In view function, what is the difference between using ‘request.form’ and ‘request.get_json()’? In my case which one is the best practice? What is the best use case for the other one?
- Why adding the headers like “Content-Type”: “multipart/form-data” will let the view funtion failed to get file when handling the request, but if I don’t add this headers it will work?
- In general, what is the best practice to implement the case that I described?