본문 바로가기

Projects/Flask + MongoDB K리그 일정서비스

#4. 상세페이지 구현 | 경기 상세정보와 댓글

# 상세 페이지
//경기인덱스를 파라미터로 받는다
@app.route("/cheer/<matchIdx>", methods=['GET'])
def cheer(matchIdx):
	
    //경기인덱스에 해당하는 경기정보를 불러온다
    match = db.matches.find_one({"_id": ObjectId(matchIdx)})
    
    //경기일정에 맞게 경기정보를 정렬한다
    contents = list(db.contents.find({"match_idx": ObjectId(matchIdx)}).sort('cheer_datetime', -1))
    
    //각 경기별 인덱스 값을 문자열로 바꾼다
    for content in contents:
        content["_id"] = str(content["_id"])

	//토큰을 꺼내서
    token_receive = request.cookies.get('mytoken')
    try:
    	//토큰의 유저정보에 해당하는 아이디를 찾아서
        payload = jwt.decode(token_receive, SECRET_KEY, algorithms=['HS256'])
        user_info = db.users.find_one({"user_id": payload["id"]})
        
        //경기정보와 유저정보를 상세페이지에 함께 렌더링한다
        return render_template('cheer.html', match=match, contents=contents, user_info=user_info)

    except jwt.ExpiredSignatureError:
        return redirect(url_for("login", msg="로그인 시간이 만료되었습니다."))
    except jwt.exceptions.DecodeError:
        return redirect(url_for("login", msg="로그인 정보가 존재하지 않습니다."))

몽고DB에서 각 객체는 특정한 id값을 가진다. 이것을 경기번호(인덱스)처럼 활용할 수 있다. 따라서 특정 경기정보와 로그인한 유저정보를 함께 상세페이지에 렌더링해줄 수 있다.

 

이렇게 하면,

1) 특정 경기정보를 jinja2를 활용해 cheer.html에 찍어줄 수 있으며,

2) cheer.html에서 댓글을 달 때, 경기정보와 함께 렌더링한 유저정보를 jinja2로 찍어서 누가 댓글을 달았는지 표시해줄 수 있다.

 

그렇다면 이제는 댓글작성 기능을 구현해보자.

 

# 글 작성
@app.route("/api/set_cheer", methods=['POST'])
def set_cheer():
	
    //유저정보는 상세페이지 렌더링 시 같이 전달해주었다.
    //이것을 그대로 post요청에 담아서 보내면 된다.
    userId = request.form['userId']
    nickName = request.form['nickName']
    matchIdx = request.form['matchIdx']
    cheer_team = request.form['cheerTeam']
    cheer_content = request.form['content']
    now = datetime.now()
    nowDatetime = now.strftime('%Y-%m-%d %H:%M:%S')

    doc = {
        'user_id': userId,
        'nick_name': nickName,
        'match_idx': ObjectId(matchIdx),
        'cheer_team': cheer_team,
        'cheer_content': cheer_content,
        'cheer_datetime': nowDatetime
    }

    db.contents.insert_one(doc)
    return jsonify({'msg': '저장완료'})

앞서서 상세 페이지 렌더링 시, 유저정보와 경기상세정보를 함께 렌더링했기 때문에, 댓글작성시에는 이러한 유저정보와 경기정보 그리고 작성한 댓글내용을 함께 저장하면 된다.