I have a form where a user can upload images/videos. I create a unique image/video name for the files, to make sure the name is unique I am using the id of the image/video object. To get the id before the commit()
I am using flush()
.
def profile_add_user_post():
form = AddUserPostForm()
if form.validate_on_submit():
new_post = Post(title=form.title.data.strip(), description=form.description.data, created_on=datetime.today(), updated_on=datetime.today(), created_by_user_id=current_user.id)
if form.visible_to_tier_id.data and form.visible_to_tier_id.data != "0":
setattr(new_post, "visible_to_tier_id", form.visible_to_tier_id.data)
if form.post_image.data:
new_image_post = PostImage(path=get_random_code(15), created_on=datetime.today())
new_post.image_belongs_to_post_addresses.append(new_image_post)
# multiple add
db_session.add(new_post)
db_session.flush()
image_name = str(new_image_post.id) + "-post-image." + form.post_image.data.filename.split(".")[-1]
upload_to_aws(image_name, "images/", form.post_image.data)
setattr(new_image_post, "path", image_name)
if form.post_video.data:
new_video_post = PostVideo(path=get_random_code(15), created_on=datetime.today())
new_post.video_belongs_to_post_addresses.append(new_video_post)
# multiple add
db_session.add(new_post)
db_session.flush()
video_name = str(new_video_post.id) + "-post-video." + form.post_video.data.filename.split(".")[-1]
upload_to_aws(video_name, "videos/", form.post_video.data)
setattr(new_video_post, "path", video_name)
if form.send_category.data:
category_list_for_post = form.send_category.data.split(",")
for cat in category_list_for_post:
new_cat_post = PostBelongsCategory(category_id=cat)
new_post.children_PostBelongsCategory.append(new_cat_post)
# multiple add
db_session.add(new_post)
db_session.commit()
flash("Beitrag erfolgreich hinzugefügt","success")
return redirect(url_for('profile'))
return render_template('profile_add_post.html', form=form)
It works great, but couldn't this lead to problems with IntegretyError
?
A video upload can take a few minutes. But I am asking for the ID before the video has been uploaded, in case another user uploads a video at the same time. The flush()
could make it possible for both users to have the same video ID, which would lead to one of them to an IntegretyError
while uploading the video.
So is this an issue in my example? If yes what is the use of flush()
? I have already found some threads about this but I am not 100% sure yet.
Also if flush()
is not useful here, how can I make sure (best practice) that the filenames are unique?
I could use my get_random_code(15)
for the filename, which would generate a random string, the chance that the same string would be generated twice is almost 0. This way I wouldn't need flush()
. But I do not have more ideas.