IT/프로그래밍

[파이썬] 파이썬 1차 프로젝트 블로그 만들기 마지막 [패스트 캠퍼스 챌린지 21일]

뜻밖의 행복 2022. 2. 13. 23:19
반응형

안녕하세요?

오늘 드디어 파이썬 기초 마지막 강의 였네요

이거 끝나면 심화 과정에 들어갑니다.

그래도 계속 반복해서 제것으로 만들어야 겠습니다.

 

그리고 어느덧 반에 가까운 21일이 되었네요 

시간 참 빠릅니다. 

22년도 벌써 2월 반이 흘러가고 있습니다.

 

22년 뭔가 해야 하는데 

 

 

오늘은 게시글 수정, 삭제, 저장 3가지 기능 구현 입니다.

이 기능 구현으로 블로그 구현이 되었네요

 

오늘까지 배운 것으로 최종 만들어진 내용입니다.

import os
import csv
from post import Post

# 파일 경로
file_path = "./myvenv/theone/data.csv"

# post 객체를 저장할 리스트
post_list = []

# data.csv 파일이 있다면
if os.path.exists(file_path):
    # 게시글 로딩
    print("게시글 로딩중...")
    f = open(file_path, "r", encoding="utf8")
    reader = csv.reader(f)
    for data in reader:
        # Post 인스턴스 생성하기
        post = Post(int(data[0]), data[1], data[2], int(data[3]))
        post_list.append(post)
else:
    # 파일 생성하기
    f = open(file_path, "w", encoding="utf8", newline="")
    f.close()

# 게시글 쓰기
def write_post():
    print("\n\n- 게시글 쓰기 -")
    title = input("제목을 입력해 주세요\n>>>")
    content = input("내용을 입력해 주세요\n>>>")
    # 글번호 
    id = post_list[-1].get_id() + 1
    post = Post(id, title, content, 0)
    post_list.append(post)
    print("# 게시글이 등록되었습니다.")

# 게시글 목록
def list_post():
    print("\n\n- 게시글 목록 -")
    id_list = []
    for post in post_list:
        print("번호 :", post.get_id())
        print("제목 :", post.get_title())
        print("조회수 :", post.get_view_count())
        print("")
        id_list.append(post.get_id())
    
    while True:
        print("Q) 글 번호를 선택해 주세요 (메뉴로 돌아가려면 -1을 입력해주세요)")
        try:
            id = int(input(">>>"))
            if id in id_list:
                detail_post(id)
                break
            elif id == -1:
                break
            else:
                print("없는 글 번호 입니다.")
        except ValueError:
            print("숫자를 입력해 주세요")

# 글 상세 페이지
def detail_post(id):
    print("\n\n- 게시글 상세 -")

    for post in post_list:
        if post.get_id() == id:
            # 조회수 1증가
            post.add_view_count()
            print("번호 :", post.get_id())
            print("제목 :", post.get_title())
            print("본문 :", post.get_content())
            print("조회수 :", post.get_view_count())
            target_post = post

    while True:
        print("Q) 수정: 1 삭제: 2 (메뉴로 돌아가려면 -1을 입력)")
        try:
            choice = int(input(">>>"))
            if choice == 1:
                update_post(target_post)
                break
            elif choice == 2:
                delete_post(target_post)
                break
            elif choice == -1:
                break
            else:
                print("잘못 입력하였습니다.")
        except ValueError:
            print("숫자를 입력해 주세요")

# 게시글 수정
def update_post(target_post):
    print("\n\n- 게시글 수정 -")
    title = input("제목을 입력해 주세요\n>>>")
    content = input("본문을 입력해 주세요\n>>>")
    target_post.set_post(target_post.id, title, content, target_post.view_count)
    print("# 게시글이 수정되었습니다.")

# 게시글 삭제
def delete_post(target_post):
    post_list.remove(target_post)
    print("# 게시글이 삭제되었습니다.")

# 게시글 저장
def save():
    f = open(file_path, "w", encoding="utf8", newline="")
    writer = csv.writer(f)
    for post in post_list:
        row = [post.get_id(), post.get_title(), post.get_content(), post.get_view_count()]
        writer.writerow(row)
    f.close()
    print("# 저장이 완료 되었습니다.")
    print("# 프로그램 종료")

# 메뉴 출력하기
while True:
    print("\n\n- FASTCAMPUS BLOG -")
    print("- 메뉴를 선택해 주세요 -")
    print("1. 게시글 쓰기")
    print("2. 게시글 목록")
    print("3. 프로그램 종료")
    try:
        choice = int(input(">>>"))
    except ValueError:
        print("숫자를 입력해 주세요")
    else:
        if choice == 1:
            write_post()
        elif choice == 2:
            list_post()
        elif choice == 3:
            save()
            break

 

비쥬얼 스튜디어로 보니 대충 130줄 정도 됩니다. 

130줄에 이런 기초적인 블로그 기능이 다 구현이 된다는게 너무 신기하네요 

단지 GUI 가 없어서 조금 초라하지만 

핵심 기능은 다 구현이 되어 있다는 것에 의의를 두겠습니다.

 

잘 작동하네요 

 

이중 오늘 구현한 기능 3가지

 

# 게시글 수정
def update_post(target_post):
    print("\n\n- 게시글 수정 -")
    title = input("제목을 입력해 주세요\n>>>")
    content = input("본문을 입력해 주세요\n>>>")
    target_post.set_post(target_post.id, title, content, target_post.view_count)
    print("# 게시글이 수정되었습니다.")

# 게시글 삭제
def delete_post(target_post):
    post_list.remove(target_post)
    print("# 게시글이 삭제되었습니다.")

# 게시글 저장
def save():
    f = open(file_path, "w", encoding="utf8", newline="")
    writer = csv.writer(f)
    for post in post_list:
        row = [post.get_id(), post.get_title(), post.get_content(), post.get_view_count()]
        writer.writerow(row)
    f.close()
    print("# 저장이 완료 되었습니다.")
    print("# 프로그램 종료")

 

차근 차근 살펴보겠습니다.

 

# 게시글 수정
def update_post(target_post):
    print("\n\n- 게시글 수정 -")
    title = input("제목을 입력해 주세요\n>>>")
    content = input("본문을 입력해 주세요\n>>>")
    target_post.set_post(target_post.id, title, content, target_post.view_count)
    print("# 게시글이 수정되었습니다.")

게시글 수정 함수를 정의 합니다. 인자는 게시글 지난글에서 게시글 목록 조회에서 나왔던 것을 받아서 수정합니다.

target_post라는 변수입니다. 

Post 매서드에서 정의한 set_post를 이용해서 사용자에게 입력 받은 제목, 본문으로 게시글을 수정하게끔 구현하였습니다. 

 

# 게시글 삭제
def delete_post(target_post):
    post_list.remove(target_post)
    print("# 게시글이 삭제되었습니다.")

게시글 삭제는 너무 쉽습니다. 

사실 이미 구현되어 있는 매서드를 가져다 사용하면 끝입니다. 

이름도 remove 입니다. 

post_list에서 뒤에 remove 매서드 안에 삭제가 필요한것만 저렇게 넣으면 

알아서 삭제가 됩니다. 

거의 보너스 수준이네요

 

# 게시글 저장
def save():
    f = open(file_path, "w", encoding="utf8", newline="")
    writer = csv.writer(f)
    for post in post_list:
        row = [post.get_id(), post.get_title(), post.get_content(), post.get_view_count()]
        writer.writerow(row)
    f.close()
    print("# 저장이 완료 되었습니다.")
    print("# 프로그램 종료")

 

드디어 마지막 저장 입니다. 

파일 open / close는 한몸이라 꼭 열고 닫는 것을 잊으면 안됩니다. 

우선 파일을 open함수를 통해서 'w' 쓰기 모드로 열어서 f 에 저장합니다.

그리고 CSV파일에 한라인씩 저장하기 위해서 for 문을 이용하여 저장합니다.

 

이 것으로 오늘 최종 구현이 끝났는데 저는 한번 더 복습해야겠습니다.

 

반응형