I am currently writing a machine flask application where users upload an image to flask via a form, this image is then processed and the output is spit out by the model and served on flask.
Currently as soon as the user presses the "submit" button on the form, I have the code check if the "upload" folder (located in the same directory as the main.py folder) is empty, and if it isn't I have it empty it. Then the file submitted by the user is placed in that upload folder.
Basically I only want one file to ever be present in the upload folder, and it must be the file that the user submits via the form .
def upload():
"""uploads an image"""
form = UploadImage()
#if client attempts to submit the form (ie sends a POST request)
if request.method =="POST":
#first check if "upload" directory is empty. If the directory is not empty,
# delete any files that are in it: the "upload" directory functions as a 'temporary' directory, and we
# only want the one image the current client uploads to the server to ever be there
if len(os.listdir("uploads")) != 0:
for f in os.listdir("uploads"):
path_to_file = os.path.join("uploads", f)
os.remove(path_to_file)
But i think that coded this way, this unique upload folder that the os module writes to every time a post request is successful is a bad idea. What happens if two or multiple users connect to the app and send a POST request to the server at the same time? We would have two users trying to write to the same upload folder at the same time, which might break the app.
So I was thinking of either substituting this "upload" folder with a temporary folder that is generated every time a user presses the submit button, OR using a lock/semaphor around the part of code where the os writes to the "upload" folder, to ensure that only one user can only ever write to that folder at a time..
Out of the two options which would be the better one to implement in the flask application, and why? many thanks for the help