IT/프로그래밍

[파이썬] 파이썬 1차 프로젝트 블로그 만들기 4번째 [패스트 캠퍼스 챌린지 20일]

뜻밖의 행복 2022. 2. 12. 22:45
반응형

안녕하세요? 뜻밖의 행운 입니다. 

오늘로 패스트 캠퍼스 챌린지 20일차이네요 

주말에도 쉬지 않고 가겠습니다.

 

사실 강의 하나하나가 길지는 않아서 짧게 짧게 들으면서 계속 할 수 있었습니다.

오늘 계속해서 블로그 만들기 입니다.

 

 

오늘 구현할 것은 게시글 목록이 나오게 하는 것과 게시글 상세 보기 기능입니다.

 

import os
import csv
from post import Post

# 파일 경로
file_path = "./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("숫자를 입력해 주세요")

# 메뉴 출력하기
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

이것이 오늘까지 진행한 내용입니다 .

지난번에 이어 추가 된 내용은 게시글 목록 보기와, 게시길 상세 보기 입니다.

각각 내용을 좀 상세히 볼까요?

 

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 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())

해당 기능 선택시 print 문으로 게시글 목록을 출력하고 그 아래에 

클래스로 정의한 post 메서드를 이용하여 

각각 글 번호, 제목, 조회수를 출력 해서 게시글 형태로 보이게 합니다. 

for 문으로 출력해가면서 글 번호는 id_list 를 활용하여 list로 관리합니다.

 

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("숫자를 입력해 주세요")

제 메뉴 화면이니까 계속 while true로 화면에 뿌려 줍니다. 

글 번호를 선택하라고 이용자한테 요청을 한 상태니 

id 로 글번호를 입력 받습니다. 숫자를 받을 테니 정수형 int()로 처리하구요 

그리고 익숙하죠 ? trt-except으로 숫자가 아닌 값을 입력했을때 프로그램이 error로 죽지 않게

처리 해줍니다. Value Error 

 

그리고 id 를 사용자가 정상적으로 입력했을 경우 

목록에 있는 id를 입력 했을 때는 detail_post(id) 함수를 실행(여기서는 아직 정의 하지 않았지요 아래에 있습니다.)

그리고 목록에 없는 id를 입력했을 때 또 이용자에게 제대로 입력하라고 안내 문을 뿌려주게 

조건문 분기를 나눕니다.

이렇게 해서 게시글 목록 구현은 끝났구요 이어서

 

# 글 상세 페이지 확인
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 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

detail_post(id) 함수를 정의 해야 합니다. 

게시글 목록에서 호출하는 함수지요 

 for post in post_list:

        if post.get_id() == id:

역시 post_list의 내용을 post에 할당하면서 

사용자가 입력한 id 값이 post.get_id()에서 나온 값과 일치 한다면

그 것이 사용자가 선택한 게시글이므로 

print를 이용하여 해당 글을 출력하게 합니다. 

그리고 해당 글을 조회한것이니 조회수를 올려야 겠죠?

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("숫자를 입력해 주세요")

그리고 해당 글을 수정하거나 삭제 혹은 메인 메뉴로 돌아갈지를 선택하는 기능을 추가합니다.

이용자 선택을 해야하니 choice에 변수를 입력 받습니다. 

역시 숫자를 입력 받는거니 try-except으로 처리를 해주고

각각 선택을 받습니다. 다만 1, 2 는 아직 구현을 하지 않았으니 넘어갑니다. 

 

나중에 글이 많을 경우 비효율적인 코드도 보이는데요 

이런것을 어떻게 최적화 할지 고민하는 것도 바로 개발의 즐거움입니다.

 

이 간단한 프로젝트 끝나면 심화 과정이라고 하는데 

 

기대 되네요!

 

반응형