Python/Python Flask

Flask-Blueprint로 애플리케이션 구조화하기

임베디드 친구 2025. 9. 21. 22:30
728x90
반응형

Flask-Blueprint로 애플리케이션 구조화하기

Flask는 가볍고 유연한 프레임워크로 소규모부터 대규모 애플리케이션까지 다양한 규모의 프로젝트에 적합합니다. 그러나 애플리케이션이 커짐에 따라 코드를 체계적으로 관리하기 위해서는 구조화가 필요합니다. 이 글에서는 Flask의 Blueprint 기능을 활용해 애플리케이션을 구조화하는 방법을 알아보겠습니다.


Blueprint란 무엇인가?

Blueprint는 Flask에서 제공하는 기능으로, 애플리케이션을 모듈화하여 관리할 수 있게 해줍니다. 이를 통해 애플리케이션의 각 부분을 독립적으로 개발하고 테스트할 수 있습니다. Blueprint는 다음과 같은 장점을 제공합니다:

  • 코드 모듈화: 라우트, 뷰 함수, 템플릿 등을 독립적으로 관리할 수 있습니다.
  • 협업 향상: 팀에서 각자 Blueprint 단위로 작업 가능.
  • 재사용성: 공통 기능을 여러 프로젝트에서 재사용할 수 있습니다.

Blueprint를 사용한 애플리케이션 구조화

간단한 블로그 애플리케이션을 예로 들어, Blueprint를 사용하여 구조화하는 과정을 단계별로 살펴보겠습니다.

디렉토리 구조

다음과 같은 디렉토리 구조를 구성합니다:

project/
├── app/
│   ├── __init__.py
│   ├── routes/
│   │   ├── __init__.py
│   │   ├── blog.py
│   │   ├── auth.py
│   ├── templates/
│   │   ├── blog/
│   │   └── auth/
│   ├── static/
├── run.py

단계 1: Flask 애플리케이션 초기화

app/__init__.py

from flask import Flask

def create_app():
    app = Flask(__name__)

    # Blueprint 등록
    from .routes.blog import blog_bp
    from .routes.auth import auth_bp

    app.register_blueprint(blog_bp, url_prefix='/blog')
    app.register_blueprint(auth_bp, url_prefix='/auth')

    return app

create_app() 함수는 Flask 애플리케이션의 팩토리 함수로, 다양한 설정과 Blueprint를 등록하는 역할을 합니다.


단계 2: Blueprint 생성

app/routes/blog.py

from flask import Blueprint, render_template

blog_bp = Blueprint('blog', __name__, template_folder='../templates/blog')

@blog_bp.route('/')
def blog_home():
    return render_template('home.html')

@blog_bp.route('/post/<int:post_id>')
def blog_post(post_id):
    return f"Viewing post {post_id}"

app/routes/auth.py

from flask import Blueprint, render_template

auth_bp = Blueprint('auth', __name__, template_folder='../templates/auth')

@auth_bp.route('/login')
def login():
    return render_template('login.html')

@auth_bp.route('/logout')
def logout():
    return "Logged out"

각 Blueprint는 서로 독립적이며 필요한 라우트와 뷰를 정의합니다.


단계 3: 실행 스크립트 작성

run.py

from app import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True)

단계 4: 템플릿 작성

app/templates/blog/home.html

<!DOCTYPE html>
<html>
<head>
    <title>Blog Home</title>
</head>
<body>
    <h1>Welcome to the Blog!</h1>
</body>
</html>

app/templates/auth/login.html

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login Page</h1>
</body>
</html>

Flask-Blueprint 활용의 베스트 프랙티스

  1. 명확한 역할 분리:
    • Blueprint별로 특정 기능(예: 인증, 블로그 등)에 집중.
  2. 템플릿과 정적 파일의 조직화:
    • Blueprint에 따라 템플릿과 정적 파일 디렉토리를 분리.
  3. 공통 코드 관리:
    • 공통 코드(예: 데이터베이스 모델, 설정)는 별도의 모듈에서 관리.
  4. URL Prefix 활용:
    • url_prefix를 사용하여 URL 충돌 방지.

마무리

Flask의 Blueprint는 애플리케이션의 모듈화를 통해 유지보수성과 확장성을 크게 향상시킵니다. 이번 글에서 소개한 방법을 통해 대규모 Flask 애플리케이션을 보다 체계적으로 관리할 수 있기를 바랍니다. Blueprint를 활용한 구조화는 Flask 애플리케이션의 품질을 높이는 첫걸음입니다.

반응형