How to read/process an audio file sent in a POST request to a Flask API?
Answer a question
I'm running a simple Flask backend that will process HTTP requests with audio files and read the data. Eventually I will like to read the data and have an ML model perform an inference with the audio data, but the first step is to simply read the data in the proper encoding format.
My code for the Flask app is below:
@app.route('/api/audio', methods=['GET', 'POST'])
def get_score():
if request.method == 'POST':
length = request.content_length
content_type = request.content_type
data = request.data
return f"""Content Type is {content_type} and data is {data} \n length is {length}"""
elif request.method == 'GET':
return 'get method received'
My test code on the client side generating the POST request is below:
def send_audio():
#print('attempting to send audio')
url = 'http://127.0.0.1:5000/api/audio'
with open('/Users/kaushikandra/laughter-detection/LaughDetection/crowd_laugh_1.wav', 'rb') as file:
data = {'uuid':'-jx-1', 'alarmType':1, 'timeDuration':10}
files = {'messageFile': file}
req = requests.post(url, files=files, json=data)
print(req.status_code)
print(req.text)
I get the following output from the server when I run the client script.
200
Content Type is multipart/form-data; boundary=d95c72e01bdfac029b16da2b8f144cbd and data is b''
length is 129722
I can see from the 200 status code that the flask app is correctly receiving the POST request, but when I try to read the data I get an empty b'' string. What is the proper method to use to decode the audio file? or is the problem with the way I'm sending the POST request in the client script?
I've looked at other questions on StackOverflow and they have mentioned to send the file as a part of the 'files' parameter in the POST request.
Answers
Try using request.files to get your audio file:
@app.route('/api/audio', methods=['GET', 'POST'])
def get_score():
if request.method == 'POST':
request.files['messageFile']
Also request.data is just an empty string if I recall. Use request.json() or request.get_json(force=True).
更多推荐

所有评论(0)