Jul 2nd - Optimized code 6

This commit is contained in:
2026-07-02 17:25:19 -04:00
parent d2ea7174ba
commit 3c31c7a491
5 changed files with 107 additions and 44 deletions
+17 -6
View File
@@ -617,15 +617,26 @@ def kb_delete_attachment(article_id, att_id):
att = KBAttachment.query.filter_by(id=att_id, article_id=article_id).first_or_404()
upload_dir = current_app.config['UPLOAD_FOLDER']
filepath = os.path.join(upload_dir, att.stored_name)
if os.path.exists(filepath):
os.remove(filepath)
log_action(current_user.id, 'kb_attachment_delete', 'kb_attachment', att.id,
f'article_id={article_id} filename={att.filename}')
logger.info(f'[KB ATTACHMENT DELETE] att_id={att.id} article_id={article_id} by user_id={current_user.id}')
att_id_val, filename = att.id, att.filename
# DB row is the source of truth — delete and commit it first, then remove
# the physical file. If the process dies mid-operation this leaves at
# worst an orphan file on disk (harmless, cleanable later) rather than a
# DB row pointing at a file that's already gone (a broken download link).
log_action(current_user.id, 'kb_attachment_delete', 'kb_attachment', att_id_val,
f'article_id={article_id} filename={filename}')
db.session.delete(att)
db.session.commit()
logger.info(f'[KB ATTACHMENT DELETE] att_id={att_id_val} article_id={article_id} by user_id={current_user.id}')
if os.path.exists(filepath):
try:
os.remove(filepath)
except OSError as exc:
logger.warning(f'[KB ATTACHMENT DELETE] Could not remove file {filepath}: {exc}')
# Return JSON so the edit page can remove the row without a full reload
return jsonify({'ok': True, 'att_id': att.id})
return jsonify({'ok': True, 'att_id': att_id_val})