파이썬(Python)/Flask

파이썬 blueprint 란? 간단한 예제로 이해해보기(flask, python)

끄적끄적아무거나 2021. 5. 24. 22:05
반응형

Python flask blueprint


blueprint란?

 

blueprint를 간단하게 설명하면 우리가 윈도우에서 게임은 게임별로 사진은 사진별로 깔끔하게 폴더를 정리하듯이 blueprint는 flask에서 제공하는 라이브러리로 페이지나 기능에 맞게 백엔드를 분류해서 사용하기 편하게 해준다. 

 

사용법을 간단히 말하면 아래와 같다.

 

1. "from flask import Blueprint" 를 해서 blueprint를 가져온다.

2. Blueprint를 사용하여 객체를 만들고 만들어진 객체를 통해 동일한 url로 묶어 준다. 가령 책을 읽는 페이지와 쓰는 페이지를 책이라는 url에 묶어서 /book/write와 /book/read 를 쓸때 /book 이라는 url로 묶은 것이다. 자세한 내용은 아래 예제를 통해 쉽게 이해하길 바란다.

3. 묶고 싶은 페이지를 앞서 선언한 객체와 연결한다. 

4. register_blueprint 를 통해 해당 blueprint를 등록한다.

 

설명은 어렵지만 아래 예제 코드를 보면 쉽게 이해될 것이다. 

 


예제를 통해 이해하기

 

 

폴더구성>>

그림1

 

코드 - run.py>>

from main import app

if __name__ == "__main__":
    app.run(host = "0.0.0.0", port = 9999, debug = True)

 

코드 - __init__.py>>

from flask import Flask
from . import book
from . import city

app = Flask(__name__)

app.register_blueprint(book.blue_book)
app.register_blueprint(city.blue_city)

 

코드 - book.py>>

from flask import Blueprint

blue_book = Blueprint("book", __name__, url_prefix="/book")

@blue_book.route("/read")
def read():
    return "this is read"

@blue_book.route("/write")
def write():
    return "this is write"

 

코드 - city.py>>

from flask import Blueprint

blue_city = Blueprint("city", __name__, url_prefix="/city")

@blue_city.route("/seoul")
def seoul():
    return "this is Seoul"

@blue_city.route("/busan")
def busan():
    return "this is busan"

 

결과>>

 

주석 >>

 

__init__.py 는 폴더의 파이썬 파일 중에 가장 먼저 실행된다. app 이라는 flask 객체를 만들어서 여기서 blueprint를 등록해주는 작업(regiter_blueprint)을 하였다.

book.py 는 http://localhost:9999/book/ 주소로 시작할 route를 묶어주었고 city.py는 http://localhost:9999/city/로 시작하는 route를 묶어 주었다. (url_prefix를 사용해서 묶어줌) 그리고 결과 처럼 실행하니 원하는 주소에서 예상한 return 값이 나왔다. 

 

위 예제는 단순한 예를 보여 준것으로 웹페이지가 복잡해지면 그때 blueprint 효율이 늘어난다. 

 

 

 

반응형