HTTP upload : skip if file exists

This commit is contained in:
ABelliqueux 2022-11-08 15:28:53 +01:00
parent e3744e5b56
commit 894a4c5e76
2 changed files with 27 additions and 6 deletions

31
app.py
View File

@ -60,6 +60,7 @@ def allowed_ext(filename):
# Split from right at first dot to find ext and allow files with "." in name
if filename.rsplit(".",1)[-1] in media_exts:
return True
def XMLify(string, child_node_name="child"):
'''
'''
@ -120,7 +121,22 @@ def thread_blink():
'''
th = threading.Thread(target=blink_pi, args=(16,))
th.start()
def list_media_files(folder):
'''
List files in folder which extension is allowed (exists in media_exts).
'''
if os.path.exists(folder):
files = os.listdir(folder);
medias = []
for fd in files:
if len(fd.split('.')) > 1:
if fd.split('.')[1] in media_exts:
medias.append(fd)
return medias
else:
return []
@app.route("/")
@auth.login_required
def main():
@ -157,7 +173,6 @@ def shutdown():
@auth.login_required
def upload_file():
if request.method == "POST":
# TODO : First check name/size of file to avoid uploading if already exists ?
# Check if the post request has the file part
if "file" not in request.files:
return _("No file part: {}").format(str(request.files))
@ -167,9 +182,15 @@ def upload_file():
if file.filename == "":
return _("No selected file")
if file and allowed_ext(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(upload_folder, filename))
return _("File saved in {}").format(upload_folder)
if debug:
print("Uploading file {} in {}.".format(str(file.filename, upload_folder)))
if file.filename not in list_media_files(upload_folder):
if debug:
print("Existing files : {}".format(str(list_media_files(upload_folder))))
filename = secure_filename(file.filename)
file.save(os.path.join(upload_folder, filename))
return _("File saved in {}").format(upload_folder)
return "File exists, skipping..."
return "OK"
if __name__ == '__main__':

View File

@ -1,5 +1,5 @@
[DEFAULT]
debug = 0
debug = 1
auth = "secret"
media_folder_local = "~/Videos"
media_exts = ["mp4", "avi", "mkv"]