ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • RestX 에서 Namespace, Blueprint 사용하기
    flask 2022. 6. 28. 12:42

     

    문제

    https://flask-restx.readthedocs.io/en/latest/scaling.html 에 나오는 Namespace, Blueprint 사용을 정리해 본다.

     

    구조

    ├── apis
    │   ├── namespace1.py
    │   └── namespace2.py
    └── app.py

     

    코드

    apis/namespace1.py

    from flask_restx import Resource, Namespace
    
    ns1 = Namespace('cats', description='Cats related operations')
    
    
    @ns1.route('/hello')
    class Hello(Resource):
      def get(self):
        return {'hello': 'cats'}

     

     

    apis/namespace2.py

    from flask_restx import Resource, Namespace
    
    ns2 = Namespace('dogs', description='Dogs related operations')
    
    
    @ns2.route('/hi')
    class Hello(Resource):
      def get(self):
        return {'hi': 'dogs'}

     

    app.py

    from flask import Blueprint
    from flask import Flask
    from flask_restx import Api
    
    from apis.namespace1 import ns1
    from apis.namespace2 import ns2
    
    
    def get_v1() -> Blueprint:
      blueprint = Blueprint('api_1', __name__, url_prefix='/api/v1')
      api = Api(blueprint, title='My Service V1', version='1.0', description='My Description 1')
      api.add_namespace(ns1)
      return blueprint
    
    
    def get_v2() -> Blueprint:
      blueprint = Blueprint('api_2', __name__, url_prefix='/api/v2')
      api = Api(blueprint, title='My Service V2', version='2.0', description='My Description 2')
      api.add_namespace(ns1)
      api.add_namespace(ns2)
      return blueprint
    
    
    app = Flask(__name__)
    app.register_blueprint(get_v1())
    app.register_blueprint(get_v2())

     

    실행

     

    export FLASK_APP=app:app
    flask run

     

    확인

    http://127.0.0.1:5000/api/v2/ 에서 아래와 같이 확인할 수 있다.

     

    아래 Endpoints 로 조회할 수 있다.

    http://127.0.0.1:5000/api/v2/cats/hello

    http://127.0.0.1:5000/api/v2/dogs/hi

     

     

    http://127.0.0.1:5000/api/v1/ 으로 v1 version 도 확인할 수 있다.

    'flask' 카테고리의 다른 글

    Flask 기본 App 개발  (0) 2022.07.03

    댓글

Designed by Tistory.