samedi 26 septembre 2020

Rename files while being uploaded in Flask?

I have a form on which people can upload multiple files:

class MyForm(FlaskForm):
    pictures=MultipleFileField('Upload', validators=[FileAllowed(['jpg','jpeg']), DataRequired()])
    submit=SubmitField("Submit")

But the order of files is important for my program. I want Python to rename them while they're being uploaded one by one.

I thought of renaming them according to the exact time they're uploaded. So I created this function in my views.py:

def saverename(picture):
    dateTimeObj = datetime.now()
    order = os.path.join(str(dateTimeObj.month) + 
                            str(dateTimeObj.hour) +
                            str(dateTimeObj.microsecond))
    path = os.path.join(app.root_path, 'inferfiles', current_user.username.replace(" ", "_"))
    picture_name, _ext = os.path.splitext(picture.filename)
    picture_name = order
    picture_path = os.path.join(path, picture_name)
    picture_full = picture_path + _ext
    picture = Image.open(picture)
    picture = picture.resize([900, 1300])
    picture.save(picture_full, quality=80)

But the problem is, microseconds sometimes writes 5 digits instead of 6 digits and this destroyes the whole process of ordering the files by their date.

I could use something like this:

Picture-001
Picture-002
Picture-003
Picture-004
Picture-005

But I have no idea how to create this in views.py. Because I fear that when lots of people use the program, maybe the counter wouldn't reset since the counter is in views.py (sorry if it's a silly thing to worry, I'm new). I hope I've explained it clearly.

Therefore I'm open to any recommendations, I would be much grateful for anybody who could help me on this.

Thank you very much in advance.




Aucun commentaire:

Enregistrer un commentaire