728x90
반응형

주제 : 고객 정보 관리 시스템

 

1. 주요내용

기존의 로직을 MVC 패턴을 이용한 로직으로 변경하기

 

- Model

class CustomerModel:

    def do_I(self, customers, customer):
        customers.append(customer)
        index = len(customers) - 1
        return index
    def do_U(self, customers, customer, index):
        customers[index] = customer

 

- View

import re

class CustomerView:
    def chk_input_data(self, msg, func, upper=True):
        while True:
            x = input(msg)
            if upper:
                x = x.upper()
            if func(x):
                break
            else:
                print('잘못입력하셨습니다. 다시 입력 해 주세요.')
        return x

    def check_email_addr(email_addr):
        regex = re.compile('^[a-zA-Z][a-zA-Z0-9]{3,10}@[a-zA-Z0-9]{2,8}[.][a-zA-Z]{2,5}$') # re.compile 정규표현식 객체 바로 생성
        regex.search((email_addr))
        return regex.search(email_addr)

    def do_I(self):
        print('고객정보 입력')
        customer = { 'name':'', 'gender': '', 'email': '', 'year': 0 }
        customer['name'] = self.chk_input_data('이름을 입력하세요 : ', lambda x: True if len(x) > 2 else False) # 조건식이 참일 때 True리턴 거짓일때 False리턴
        customer['gender'] = self.chk_input_data('성별 (M/F)를 입력하세요 : ', lambda x: True if x in ('M','F') else False)
        customer['email'] = self.chk_input_data('이메일 주소를 입력하세요 : ', lambda x: True if self.check_email_addr(x) else False)
        customer['year'] = self.chk_input_data('출생년도 4자리 입력하세요 : ', lambda x: True if len(x) == 4 and x.isdigit() else False)
        # customers.append(customer)
        # index = len(customers) - 1
        return customer

    def do_U(self):
        print('현재 고객 정보 수정')
        customer = { 'name':'', 'gender': '', 'email': '', 'year': 0 }
        customer['name'] = self.chk_input_data('이름을 입력하세요 : ', lambda x: True if len(x) > 2 else False) # 조건식이 참일 때 True리턴 거짓일때 False리턴
        customer['gender'] = self.chk_input_data('성별 (M/F)를 입력하세요 : ', lambda x: True if x in ('M','F') else False)
        customer['email'] = self.chk_input_data('이메일 주소를 입력하세요 : ', lambda x: True if '@' in x else False)
        customer['year'] = self.chk_input_data('출생년도 4자리 입력하세요 : ', lambda x: True if len(x) == 4 and x.isdigit() else False)
        # customers[index] = customer
        return customer

 

- Controller

from customer_mvc_v import CustomerView
from customer_mvc_m import CustomerModel
import sys
import pickle
import os

class CustomerController:
    def __init__(self):
        self.customers = self.do_L()
        self.index = -1
        self.customer_view =CustomerView()
        self.customer_mode =CustomerModel()

    def print_menu(self):
            return input('''
                다음 중에서 하실 작업의 메뉴를 입력하세요.
                I - 고객 정보 입력
                P - 이전 고객 정보 조회
                C - 현재 고객 정보 조회
                N - 다음 고객 정보 조회
                U - 현재 고객 정보 수정
                S - 현재 고객 정보 저장
                D - 현재 고객 정보 삭제
                Q - 프로그램 종료
            ''').upper()

    def do_P(self, customers, index):
        print('이전 고객 정보 조회')
        if index <= 0:
            print('이전 데이타로 이동 불가.')
            print(index)
        else:
            index -= 1
            print(f'{index + 1}번째 고객 정보 입니다.')
            print(customers[index])
        return index

    def do_C(self, customers, index):
        print('현재 고객 정보 조회')
        if index >= 0:
            print(f'{index + 1}번째 고객 정보 입니다.')
            print(customers[index])
        else:
            print('입력된 정보가 없습니다. 정보 입력은 I를 선택하세요.')
            print(customers[index])

    def do_N(self, customers, index):
        print('다음 고객 정보 조회')
        if index >= (len(customers) - 1):
            print('이후 데이터 이동 불가')
            print(index)
        else:
            index += 1
            print(f'{index + 1}번째 고객 정보 입니다.')
            print(customers[index])
        return index

    def do_D(self, customers, index):
        print(f'현재 고객 정보{customers[index]["name"]} 삭제')
        del customers[index]

    def do_S(self, customers):
        print('고객 정보 저장')
        try:
            with open('cust/customers.pkl', 'wb') as f:
                pickle.dump(customers, f)
        except Exception as e:
            print('저장 오류!!!', e)

    def do_L(self):
        file_path = 'cust/customers.pkl'
        if os.path.exists(file_path):
            with open(file_path, 'rb') as f:
                return pickle.load(f)
        else:
            return list()

        # Main
    def main(self):
        while True:
            menu = self.print_menu()
            if menu == 'I':
                customer = self.customer_view.do_I()
                self.index = self.customer_model.do_I(self.customers, customer)
            elif menu == 'P':
                self.index = self.do_P(self.customers, self.index)
            elif menu == 'C':
                self.do_C(self.customers, self.index)
            elif menu == 'N':
                self.index = self.do_N(self.customers, self.index)
            elif menu == 'U':
                customer = self.customer_view.do_U()
                self.index = self.customer_mode.do_U(self.customers, customer, self.index)
            elif menu == 'D':
                self.do_D(self.customers, self.index)
            elif menu == 'S':
                self.do_S(self.customers)
            elif menu == 'Q':
                self.do_S(self.customers)
                print('안녕히가세요~')
                sys.exit()
            else:
                print('잘못 입력하셨습니다. 다시 입력 해주세요')


if __name__ == '__main__':
    a = CustomerController()
    a.main()

 

728x90
반응형

+ Recent posts