I am using a flask server to return a processed image file after a request. I'm using google cloud run and from my understanding of the concurrency, I should be deleting files as I go to reduce memory usage of the instances that are spun up. For this purpose I've chosen to use NamedTemporaryFile() in a 'with' statement - my understanding is that the default behaviour is that once you exit the 'with' statement the temp file gets deleted.
This is the code I have to return the processed image.
@app.route('/')
def hello():
"image processing"
with NamedTemporaryFile() as temp:
cv2.imwrite(str(temp.name),img_processed)
return send_file(str(temp.name), mimetype='image/png')
However, since I am trying to return the function in the 'with' statement, will the temp file still be deleted? Also am I using NamedTemporaryFile() correctly? The examples I've seen use temp.write but since I am using cv2.imwrite using temp.name was the method I came up with. And is there a better way to delete files after flask send_file? - I've read about using @after_this_request but Delete an uploaded file after downloading it from Flask says it may be inconsistent.
Update: to use cv2.imwrite with NamedTemporaryFile(), I had to specify the extension of the tempfile using:
NamedTemporaryFile(suffix='.png')
otherwise the code worked fine.