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

블로그 메뉴

  • 홈

공지사항

인기 글

태그

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

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
meaningful_life

meaningful life

4.Flask restx 적용 + Swagger
Programming/Backend

4.Flask restx 적용 + Swagger

2022. 5. 29. 22:29
728x90

4.Flask restx 적용 + Swagger

flask restful을 적용하고, Swagger 적용이 되도록 하겠습니다.

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

 

flask restx 패키지 설치

pip install flask-restx

 

__init__.py 파일에 코드 추가 및 수정

from flask import Flask
from flask_restx import Api
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy

api = Api(
    version='1.0',
    title='toy_project',
    prefix='/api',
    contact='',
    contact_email='email address',
    description="desc",
)
db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)

    # rest api
    api.init_app(app)

    # config
    config = app.config.get('ENV')
    if config == 'production':
        app.config.from_object('config.ProductionConfig')
    elif config == 'testing':
        app.config.from_object('config.TestingConfig')
    else:
        app.config.from_object('config.DevelopmentConfig')

    # database
    from toy.models import example_models
    db.init_app(app)
    migrate.init_app(app, db)

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

    return app

 

toy.controllers.example_controllers.py 파일 수정

from flask_restx import Namespace, Resource

import toy.services.example_services as example_services

example = Namespace(name='example', path='/example', description='This api is Example for first')

@example.route('/')
class ExampleRoute(Resource):
    def get(self) -> str:
        """return hello world"""
        data = 'hello_world'
        result = example_services.example_route(data=data)
        return {"result": result}

@example.route('/<int:user_number>')
@example.doc(params={'user_number': '파라미터로 입력된 숫자'})
@example.header('content-type', 'application/json')
class ExampleRouteAddParam(Resource):
    @example.response(200, description='입력 받은 파라미터를 제곱하여 반환한다')
    def get(self, user_number: int) -> str:
        """return parameter calculator"""
        print(user_number)
        result = example_services.example_route_add_param(data=user_number)
        print(result)
        return {"result": result}

 

다음 주소 접속 시 다음과 같이 Swagger documentation 출력

http://127.0.0.1:5000

728x90

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

6.Flask error, exception general handling  (0) 2022.05.29
5.Flask sqlalchemy - get, create  (0) 2022.05.29
3.Flask Database 연결 + Config 설정  (0) 2022.04.30
2.Flask MVC 패턴 환경 구축과 Blueprint  (0) 2022.04.22
1.Flask 웹 서버 구축 시작  (0) 2022.04.20
    'Programming/Backend' 카테고리의 다른 글
    • 6.Flask error, exception general handling
    • 5.Flask sqlalchemy - get, create
    • 3.Flask Database 연결 + Config 설정
    • 2.Flask MVC 패턴 환경 구축과 Blueprint
    meaningful_life
    meaningful_life
    하루하루가 의미 있고 가치 있는 삶이 될 수 있길. 그리고 나의 추억과 각종 지식의 기록과 이를 공유함으로써 다른 사람에게도 도움이 되길...

    티스토리툴바