728x90
반응형

MVC

Model-View-Controller

  • 어플리케이션을 구성하는 다양한 방법론 중 하나로 구성요소를 3가지로 나눈 대표적인 패턴
  • JAVA기반의 Spring Framework에서 사용
  • Model : 데이터를 처리하며 DB와 상호 작용하는 인터페이스 역할을 하며, 기본적으로 DB의 복잡성에 얽매이지 않고 데이터와 상호작용할 수 있다. (백엔드)
  • View : 웹 응용 프로그램인 브라우저에서 실제 사용자에게 표시되는 프레젠테이션 로직을 처리하여 UI로 나타낸다. (프론트엔드)
  • Controller : View에서 핸들러의 흐름을 처리하거나 Model의 데이터를 처리하는 로직을 제공한다. (백엔드)
Model을 통해 데이터베이스에서 가져온 데이터를 파악하고 처리해 View로 전달된 내용을 파악한 후에 View를 통해 사용자로부터 데이터를 얻는다. 또한 Model을 통해 View를 변경하거나, 데이터를 업데이트 하여 지정된 로직을 구현한다.
 
프리젠테이션 로직? 비즈니스 로직?

프리젠테이션 로직 :  보여주기 위한 로직. 화면상의 디자인 구성을 위한 로직을 일컫는 말로써, 게시판에서의 표시하기 위한 for(or while)문 등의 사용이 여기에 해당한다.

 

비즈니스 로직 : 어떠한 특정한 값을 얻기 위해 데이터의 처리를 수행하는 응용프로그램의 일부를 말한다. 즉, 원하는 값을 얻기 위해서 백엔드에서 일어나는 각종 처리를 일컫는 말이다.

 

 

 

MVT

Model-Template-View

  • MVC를 기반으로 한 디자인 패턴
  • Python기반의 Django에서 사용
  • Model : MVC패턴의 Model과 마찬가지로 데이터 간의 인터페이스를 담당한다. (백엔드)
  • Templates : 프레임워크에서 실제 브라우저에 보이는 프레젠테이션 로직을 처리하고 사용자에게 인터페이스를 제공하는 방법을 제어하는 곳이다. (프론트엔드)
  • View : MVC의 Controller와 비슷한 역할을 한다. 따라서 View에서 모든 비지니스 로직을 처리하고, Model과 Templates간의 다리 역할을 하기도 한다.  (백엔드)

 

👍출처

https://yangtaeyoung.github.io/docs/web/mvc/

https://nitro04.blogspot.com/2020/01/django-mvc-mvt.html

728x90
반응형
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