Untitled

삭제 후 영화를 추가 했을 때, num가 중복되는 현상.

수정 전 code

@app.route('/')
def home():
   return render_template('index.html')

@app.route("/movie", methods=["POST"])
def movie_post():
    url_receive = request.form['url_give']
    star_receive = request.form['star_give']
    comment_receive = request.form['comment_give']

    test1_list = list(db.test1.find({}, {'_id': False}))

    count = len(test1_list) + 1    
	=> last_num = test1_list[len(test1_list)-1]['num']  

<좀 더 의미를 명확하게 하기위해 last_num이라고 변수명을 변경 했습니다>

	

- 총 5개의 데이터가 DB에 있다면 가장 마지막 데이터의 num은 5일것 입니다. 여기서 삭제를 실행하면, DB에는 4개의 데이터가 남죠. 그러면 위에 count는 다시 5가 되서 새로 추가되는 데이터의 num이 5로 중복되게 입력 됩니다.

-> 해결 방법은 많지만 가장 간단한 방법은 DB로 받은 test1_list에서 가장 마지막 인덱스를 검사하고, 거기에 적힌 num에 +1을 해서 새롭게 추가되는 데이터에 부여하는 것입니다.
		

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    doc = {
        'num':last_num+1,  => 여기도 수정
        'title':title,
        'image':image,
        'desc':desc,
        'star':star_receive,
        'comment':comment_receive
    }
    db.test1.insert_one(doc)

    return jsonify({'msg':'저장 완료!'})


수정 후 code

@app.route("/movie", methods=["POST"])
def movie_post():
    url_receive = request.form['url_give']
    star_receive = request.form['star_give']
    comment_receive = request.form['comment_give']

    test1_list = list(db.test1.find({}, {'_id': False}))

    last_num = test1_list[len(test1_list)-1]['num']

    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
    data = requests.get(url_receive, headers=headers)

    soup = BeautifulSoup(data.text, 'html.parser')

    title = soup.select_one('meta[property="og:title"]')['content']
    image = soup.select_one('meta[property="og:image"]')['content']
    desc = soup.select_one('meta[property="og:description"]')['content']

    doc = {
        'num': last_num+1,
        'title':title,
        'image':image,
        'desc':desc,
        'star':star_receive,
        'comment':comment_receive
    }
    db.test1.insert_one(doc)

    return jsonify({'msg':'저장 완료!'})

Untitled

클리어!!