Project

미니 프로젝트 - 파이썬 게시판 구현

choisanghyun 2022. 1. 6. 22:00
728x90

모듈 -  (게시물 클래스 정의)

class Post:
    def __init__(self,id,title,content,view_count):
        self.id=id
        self.title=title
        self.content=content
        self.view_count=view_count
    def set_post(self,id,title,content,view_count):
        self.id=id
        self.title = title
        self.content = content
        self.view_count = view_count
    def add_view_count(self):
        self.view_count += 1
    def get_id(self):
        return self.id
    def get_title(self):
        return self.title
    def get_content(self):
        return self.content
    def get_view_count(self):
        return self.view_count

if __name__=="__main__": #모듈에서 직접 자기자신을 호출했을 때
    post=Post(1,"테스트","테스트입니다",0)
    #post.set_post(1,"테스트2","테스트입니다2",0)
    post.add_view_count()
    print(f"{post.get_id()} {post.get_title()} {post.get_content()} {post.get_view_count()}")

Main (게시판 함수 정의 및 구현)

import os.path
import csv
from board import Post
#파일 경로
file_path = "./data.csv"

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


# data.csv 파일이 있다면
if os.path.exists(file_path):
    #게시글 로딩
    print("게시글 로딩중...")
    f=open(file_path,"r",encoding="utf8") #읽기 모드로 csv파일 오픈
    reader= csv.reader(f)
    for data in reader:
        #인스턴스 생성
        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()

print(post_list[0].get_title())
#게시글 쓰기
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():
    """게시글 목록 함수"""
    id_list=[]
    print("\n\n- 게시글 목록 -")
    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:
                print("게시글 상세보기")
                detail_post(id) #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())
            targetpost = post #포스트 객체 저장
    while True:
        print("Q) 수정: 1 삭제: 2 (메뉴로 돌아가려면 -1을 입력)")
        try:
            choice = int(input(">>>"))
            if choice == 1:
                update_post(targetpost) #저장한 포스트객체 넘겨주기
                break
            elif choice ==2:
                delete_post(targetpost) #저장한 포스트객체 넘겨주기
                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)

#게시글 저장
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-상현이의 게시판 -")
    print("- 메뉴를 선택해 주세요 -")
    print("1. 게시글 쓰기")
    print("2. 게시글 목록")
    print("3. 프로그램 종료")

    try:
        choice=int(input(">>>"))
    except:
        print("숫자 입력하라고")
    else:
        if choice ==1:
            write_post()
        elif choice ==2:
            print("게시글 목록")
            list_post()
        elif choice ==3:
            print("종료")
            save()
            break

알아야 둬야 할 것:

매개변수를 통해서 함수에서 다른 함수로 인스턴스 속성(변수)을 넘겨줄 수 있다

모듈에 __name__== __main__을 if문으로 작성하지 않으면 다른 파일에서 모듈을 불러올때 내용이 그대로 출력됨

 

생각해볼 것:

위 코드로는 변경되지 않은 게시물의 내용도 전부 저장을 하는데, 좀 더 효율적으로 작동되려면 변경된 게시물과 추가된 게시물만 저장하는 코드를 짜는 것도 고민해볼만 할 것 같다.

또한 게시물 데이터가 종료 후에 저장이 되는데 많은 사용자가 이용을 한다면, 데이터가 꼬이는 상황이 발생할 수 있을 것 같다. 게시물 수정 즉시 데이터가 변경되고, 게시물 작성 즉시 데이터가 추가되는 코드도 고민해봐야겠다.