TIL : 댓글삭제 기능의 오류 발견

ESH'S VELOG·2023년 5월 18일
0

어제 다 해결됐다고 생각한 문제가 오늘 수정코드를 도전해볼까 하다가 생겼다...!!

고유번호를 넣은 것까지는 좋으나..
고유번호가 삭제되고 그 자리를 다른 코드들이 받아야하는데 수정하는
코드가 없다보니 아래와 같이 num이 뒤죽박죽 섞이게 된다..!

이러면 수정할 때 6번을 수정한다고 했을 때 오류가 날것이 분명하다.
그렇다면 고유번호가 삭제되면 다시 받게하는 방법이 뭐가있을까??

from flask import Flask, render_template, request, redirect
from pymongo import MongoClient

app = Flask(name)
client = MongoClient('mongodb+srv://eshika:Mongodb123@cluster0.xrq9g7i.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta
collection = db['comments'] # 컬렉션 생성

@app.route('/', methods=['GET'])
def index():
comments = collection.find() # 모든 댓글 조회
return render_template('index.html', comments=comments)

@app.route('/add_comment', methods=['POST'])
def add_comment():
comment = request.form['comment'] # 폼에서 전달된 댓글 내용 가져오기
collection.insert_one({'comment': comment}) # 댓글 추가
return redirect('/')

@app.route('/edit_comment', methods=['POST'])
def edit_comment():
comment_index = int(request.form['comment_index'])
new_comment = request.form['new_comment']
comments = collection.find()
target_comment = comments[comment_index]
target_comment['comment'] = new_comment
collection.update_one({'_id': target_comment['_id']}, {'$set': {'comment': new_comment}})
return redirect('/')

@app.route('/delete_comment', methods=['POST'])
def delete_comment():
comment_index = int(request.form['comment_index'])
comments = collection.find()
target_comment = comments[comment_index]
collection.delete_one({'_id': target_comment['_id']})
return redirect('/')

if name == 'main':
app.run('0.0.0.0', port=5000, debug=True)

profile
Backend Developer - Typescript, Javascript 를 공부합니다.

0개의 댓글