Notice
Recent Posts
Recent Comments
Link
«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Tags
more
Archives
Today
Total
관리 메뉴

MyPrograming

인스타그램 클론코딩 (해시태그 수정/삭제) 본문

Python/python 클론코딩

인스타그램 클론코딩 (해시태그 수정/삭제)

SeongWon 2020. 4. 20. 17:49
반응형

post_createView.py

def post_createView(request):
    if request.method == "GET":
        return render(request, 'post_create.html')

    if request.method =="POST":
        user = request.user
        cursor = connection.cursor()

        # POST 내용 INSERT
        content = request.POST.get('content')
        post_img = request.FILES.get('post_img')
        hashtag = request.POST.get('hashtag')
        post_img_url = fileUpload(user, post_img)

        split_hashtag = hashtag.split(' ')

        insert_sql = "INSERT INTO post(user_id, content, post_img_src)"
        insert_sql += " VALUES ((%s) ,(%s), (%s))"

        result = cursor.execute(insert_sql, (user.username, content, post_img_url,))
        post_id = cursor.lastrowid


        # 해시태그 INSERT
        for i in range(len(split_hashtag)):
            # 이미 등록된 해시태그인지 확인
            inserted_hashtag = "SELECT COUNT(*)"
            inserted_hashtag += " FROM hashtag"
            inserted_hashtag += " WHERE keyword = (%s)"

            inserted_hashtag_result = cursor.execute(inserted_hashtag, (split_hashtag[i],))
            inserted_hashtag_datas = cursor.fetchall()

            if inserted_hashtag_datas[0][0] == 0:
                if '#' in split_hashtag[i]:

                    hashtag_sql = "INSERT INTO hashtag(keyword)"
                    hashtag_sql += " VALUES (%s)"

                    hashtag_result = cursor.execute(hashtag_sql, (split_hashtag[i],))
                    hashtag_id = cursor.lastrowid


                    # POST 해시태그 테이블 INSERT
                    post_hashtag_sql = "INSERT INTO post_hashtag(post_id, hashtag_id)"
                    post_hashtag_sql += " VALUES ((%s), (%s))"

                    post_hashtag_result = cursor.execute(post_hashtag_sql, (post_id, hashtag_id,))

            else:
                if '#' in split_hashtag[i]:
                    # 이미 존재하는 해시태그 아이디 가져오기
                    present_hashtag_sql = "SELECT hashtag_id"
                    present_hashtag_sql += " FROM hashtag"
                    present_hashtag_sql += " WHERE keyword = (%s)"

                    present_hashtag_result = cursor.execute(present_hashtag_sql, (split_hashtag[i],))
                    present_hashtag_datas = cursor.fetchall()

                    # POST 해시태그 테이블 INSERT
                    post_hashtag_sql = "INSERT INTO post_hashtag(post_id, hashtag_id)"
                    post_hashtag_sql += " VALUES ((%s), (%s))"

                    post_hashtag_result = cursor.execute(post_hashtag_sql, (post_id, present_hashtag_datas[0][0],))

        connection.commit()
        connection.close()


        return redirect('instagram:list', user.username)

해시태그는 포스트를 생성할 때, 함께 추가하기 때문에 같이 데이터베이스에 넣어준다.

 

위와 같이 해시태그를 추가하는 폼에 해당 키워드가 "#"으로 묶여있을 경우에만 데이터베이스에 추가되도록 View를 짰다.


post_modifyView.py

def post_modifyView(request, postmodify):

    if request.method == "GET":
        user = request.user

        cursor = connection.cursor()

        strSql = "SELECT post_img_src, content, post_id"
        strSql += " FROM post"
        strSql += " WHERE post_id = (%s)"

        result = cursor.execute(strSql, (postmodify,))
        datas = cursor.fetchall()

        # 해시태그 가져오기
        post_hashtag_sql = "SELECT keyword"
        post_hashtag_sql += " FROM hashtag"
        post_hashtag_sql += " LEFT OUTER JOIN post_hashtag on hashtag.hashtag_id = post_hashtag.hashtag_id"
        post_hashtag_sql += " WHERE post_id = (%s)"

        post_hashtag_sql_result = cursor.execute(post_hashtag_sql, (postmodify,))
        post_hashtag_sql_datas = cursor.fetchall()

        hashtag = []
        for i in range(len(post_hashtag_sql_datas)):
            hashtag.append(post_hashtag_sql_datas[i][0])

        hashtag_result = ' '.join(hashtag)

        connection.commit()
        connection.close()

        post = {'post_img_src': datas[0][0],
                'content': datas[0][1],
                'post_id': datas[0][2],
                'hashtag': hashtag_result}

        return render(request, 'post_modify.html', {'post': post})

    elif request.method == "POST":
        new_content = request.POST.get("content")
        new_hashtag = request.POST.get("hashtag")

        split_new_hashtag = new_hashtag.split(' ')

        cursor = connection.cursor()

        # 포스트 content 수정 삽입
        strSql = "UPDATE post"
        strSql += " SET content = (%s)"
        strSql += " WHERE post_id = (%s)"

        results = cursor.execute(strSql, (new_content, postmodify,))
        datas = cursor.fetchall()


        # 기존의 post_hashtag 삭제
        delete_post_hashtag = "DELETE"
        delete_post_hashtag += " FROM post_hashtag"
        delete_post_hashtag += " WHERE post_id = (%s)"

        delete_post_hashtag_result = cursor.execute(delete_post_hashtag, (postmodify,))

        for i in range(len(split_new_hashtag)):
            # 수정될 해시태그가 이미 테이블에 존재하는가
            inserted_hashtag = "SELECT COUNT(*)"
            inserted_hashtag += " FROM hashtag"
            inserted_hashtag += " WHERE keyword = (%s)"

            inserted_hashtag_result = cursor.execute(inserted_hashtag, (split_new_hashtag[i],))
            inserted_hashtag_datas = cursor.fetchall()

            if inserted_hashtag_datas[0][0] == 0:
                if '#' in split_new_hashtag[i]:

                    hashtag_sql = "INSERT INTO hashtag(keyword)"
                    hashtag_sql += " VALUES (%s)"

                    hashtag_result = cursor.execute(hashtag_sql, (split_new_hashtag[i],))
                    hashtag_id = cursor.lastrowid

                    # POST 해시태그 테이블 INSERT
                    post_hashtag_sql = "INSERT INTO post_hashtag(post_id, hashtag_id)"
                    post_hashtag_sql += " VALUES ((%s), (%s))"

                    post_hashtag_result = cursor.execute(post_hashtag_sql, (postmodify, hashtag_id,))

            else:
                if '#' in split_new_hashtag[i]:
                    # 이미 존재하는 해시태그 아이디 가져오기
                    present_hashtag_sql = "SELECT hashtag_id"
                    present_hashtag_sql += " FROM hashtag"
                    present_hashtag_sql += " WHERE keyword = (%s)"

                    present_hashtag_result = cursor.execute(present_hashtag_sql, (split_new_hashtag[i],))
                    present_hashtag_datas = cursor.fetchall()

                    # POST 해시태그 테이블 INSERT
                    post_hashtag_sql = "INSERT INTO post_hashtag(post_id, hashtag_id)"
                    post_hashtag_sql += " VALUES ((%s), (%s))"

                    post_hashtag_result = cursor.execute(post_hashtag_sql, (postmodify, present_hashtag_datas[0][0],))

        connection.commit()
        connection.close()

        return redirect('instagram:detail', postmodify)

포스트를 수정하는 과정에서 해시태그를 수정하게 되는 경우 기존에 그 게시글과 연결되었던 해시태그들은 모두 삭제해주고 새롭게 등록해주는 것이 좋다.

이미 존재하는 해시태그인지, 아예 새로운 해시태그인지를 구분하여 데이터베이스가 추가할지를 판단하여 넣어준다.

또한 처음에 생성했던 해시태그를 지우고 다른 해시태그를 넣는 경우에도 기존의 해시태그는 사라지지 않는다.

 

수정전 게시글의 해시태그

 

포스트 수정페이지 해시태그 부분

위와 같이 일부 해시태그는 그대로 두고, 원래 있던 것을 지우고 새로운 해시태그를 추가해보았다.

 

↓ 

 

 


post_deleteView.py

def post_deleteView(request, postdelete):
    user = request.user

    cursor = connection.cursor()

    strSql = "DELETE"
    strSql += " FROM post"
    strSql += " WHERE post_id = (%s)"

    result = cursor.execute(strSql, (postdelete,))

    #삭제될 게시물과 연결된 해시태그가 있는가
    post_hashtag = "SELECT post_id"
    post_hashtag += " FROM post_hashtag"
    post_hashtag += " WHERE post_id = (%s)"

    post_hashtag_result = cursor.execute(post_hashtag, (postdelete,))
    post_hashtag_datas = cursor.fetchall()

    if len(post_hashtag_datas) !=0 :
        delete_post_hashtag = "DELETE"
        delete_post_hashtag += " FROM post_hashtag"
        delete_post_hashtag += " WHERE post_id = (%s)"

        delete_post_hashtag_result = cursor.execute(delete_post_hashtag, (postdelete,))

    connection.commit()
    connection.close()

    return redirect('instagram:list', user.username)

게시글을 삭제하는 경우, 그 게시글은 완전히 삭제된다.

하지만 데이터베이스에서 해시태그 자체는 사라지지않고 유지되는 것이 인스타그램에서는 효율적이다.

반응형