meaningful_life
meaningful life
meaningful_life
전체 방문자
오늘
어제
  • 분류 전체보기 (28)
    • Programming (28)
      • Backend (25)
      • Machine Learning (1)
      • Infrastructure (2)

블로그 메뉴

  • 홈

공지사항

인기 글

태그

  • 자바
  • Kubernetes
  • flask
  • Spring
  • 백준
  • 자바의신
  • kubectl
  • Database
  • 머신러닝
  • install
  • python
  • stringbuilder
  • ubuntu
  • ufw
  • docker
  • linux
  • git
  • 쿠버네티스
  • error
  • java

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
meaningful_life

meaningful life

2.Flask MVC 패턴 환경 구축과 Blueprint
Programming/Backend

2.Flask MVC 패턴 환경 구축과 Blueprint

2022. 4. 22. 07:51
728x90

2. Flask MVC 패턴 환경 구축과 Blueprint

https://github.com/kschoi93/flask-example

서버를 구축할 때 path, db model, db connection, service, view 등 많은 것을 전부 하나의 파일에 작성하면 작성하면서도 작성 하고 나서도 유지보수 하기가 매우 어렵습니다.

그렇기 때문에 다양한 디자인 패턴을 사용하는데요

가장 많이 사용되는 MVC 패턴을 적용해 보도록 하겠습니다.

MVC 패턴에 대해서는 구글 검색을 해보시면 아주 훌륭한 자료가 많습니다

 

MVC 패턴 적용

MVC 패턴에 대해 간단하게 설명하자면

  • M(Model) : Database에 존재하는 테이블을 현재 사용하는 프레임 워크에 맞게 객체화 시켰다고 생각하면 되겠습니다.
  • V(View) : View 영어만 봐도 느껴질 것입니다. 사람들이 브라우저를 통해 웹사이트에 접속시 보여지는 화면입니다.
    다만 제가 작성하는 것은 API 형태의 서버이기 때문에 여기서 다루지 않을 예정으로
    View는 React와 같은 javascript로 만들면 되겠습니다.
  • C(Controller) : Controller 영어 그대로 컨트롤, 조종하는 것인데요, 무엇을 조종하냐?
    유저가 주소창에 url을 다음과 같이 작성할 것입니다.
    http://127.0.0.1:5000/? 이 부분을 어떻게 작성할 것이냐에 따라서 어느 메소드를 사용할 것인지 분배 또는 나누어주는 기능을 한다고 생각하시면 되겠습니다.

 

저는 다음과 같이 구성했습니다.

  • controller
  • dao (Database와 연결하는 기능을 담당)
  • model
  • service (controller에서 네가 일 처리해줘! 하고 보내는 곳입니다. 일 처리만 하는 곳이죠)
  • routes (controller들을 app에 등록하기 위해 하나로 모으는 기능을 할 것입니다)

 

Blueprint 적용

Blueprint는 route로 받는 path를 여러 파일에서 각자의 이름으로 받아 구분이 편하게 사용할 수 있는 flask에서 지원하는 기능입니다.

이 blueprint를 controller에서 받고, routes에서 종합하는 식으로 작성하겠습니다.

 

__init__.py

routes 파일의 routes_list를 app에 포함 시킬 수 있도록 app 객체를 파라미터로 넘겨 줍니다

from flask import Flask

def create_app():
    app = Flask(__name__)

    # routes list
    from .routes import routes_list
    routes_list(app)

    @app.route('/')
    def hello_world():
        return 'hello world!'

    return app

 

routes.py

넘겨 받은 app 객체에 register_bluprint를 통해 controller를 등록해줍니다

from .controllers.example_controllers import example_bp

def routes_list(app):
    app.register_blueprint(example_bp)
    return app

 

example_controllers.py

blueprint를 사용하여 http://127.0.0.1/example 라는 url path를 받고 method 형태가 “GET” 일 경우 example_route이 실행되고 example_services에게 일 처리를 넘깁니다

그리고 반환 받은 결과 값을 jsonify 를 통해 json 형태로 client에게 결과를 반환 해줍니다

from flask import Blueprint
from flask import jsonify

import toy.services.example_services as example_services

example_bp = Blueprint(name='example',
                       import_name=__name__,
                       url_prefix='/example')

@example_bp.route('/', methods=['GET'])
def example_route() -> str:
    data = 'hello_world'
    result = example_services.example_route(data=data)
    return jsonify(result=result)

@example_bp.route('/<int:user_number>', methods=['GET'])
def example_route_add_param(user_number: int) -> str:
    result = example_services.example_route_add_param(user_number)
    return jsonify(result=result)

 

example_services.py

controller에게 받은 파라미터와 자신이 가지고 있는 기능으로 일 처리를 하고 controller에게 반환 합니다.

def example_route(data: str) -> str:
    return data

def example_route_add_param(data: int) -> int:
    return data ** data

 

접속 결과

http://127.0.0.1:5000/example url에 접속한 결과 다음과 같이 데이터가 json 형태로 잘 반환 된 것을 확인 할 수 있습니다.

http://127.0.0.1:5000/example/10 , http://127.0.0.1:5000/example/777 을 접속해보면 parameter로 넘겨준 10이 제곱 계산까지 잘 되고 반환 된 것을 확인 할 수 있습니다.

728x90

'Programming > Backend' 카테고리의 다른 글

4.Flask restx 적용 + Swagger  (0) 2022.05.29
3.Flask Database 연결 + Config 설정  (0) 2022.04.30
1.Flask 웹 서버 구축 시작  (0) 2022.04.20
MariaDB + SQLAlchemy + Flask에서 database 연결 끊김 현상  (0) 2022.03.21
Spring Request 데이터를 List 형태로 받으면 @Valid 체크가 안되는 현상 해결 방법  (1) 2021.12.04
    'Programming/Backend' 카테고리의 다른 글
    • 4.Flask restx 적용 + Swagger
    • 3.Flask Database 연결 + Config 설정
    • 1.Flask 웹 서버 구축 시작
    • MariaDB + SQLAlchemy + Flask에서 database 연결 끊김 현상
    meaningful_life
    meaningful_life
    하루하루가 의미 있고 가치 있는 삶이 될 수 있길. 그리고 나의 추억과 각종 지식의 기록과 이를 공유함으로써 다른 사람에게도 도움이 되길...

    티스토리툴바