Daily Develope

[Web] Flask API 서비스별로 관리 본문

카테고리 없음

[Web] Flask API 서비스별로 관리

noggame 2023. 4. 4. 09:05

구조 (가정)

: api, test, dataset 서비스/api가 필요하고, 각 서비스/api는 도메인별로 구분하기위해 별도 페이지(소스코드)에서 관리

서비스 구현 (api / test / dataset)

: 각 서비스는 services 폴더 내에 별도 파일(소스코드)로 구현/관리한다.

### 아래 각 경로에 서비스 구현
# services/api.py
# services/test.py
# services/dataset.py

api.py 코드 예시

from flask import Blueprint, request, jsonify

api = Blueprint(name="api", import_name=__name__)

@api.route('/apis/<service>', methods=['GET'])
def my_api_service(service_name:str):
    if request.content_type != "application/json":
        return jsonify({"status_code":500})

    # implement service logic...

    return jsonify({"status_code":200, "result":"result data"})

Flask 실행 시 구현된 서비스 연결

flask 실행코드 예시

from flask import Flask
from waitress import serve
from services.api import api
from services.test import test
from services.dataset import dataset

### Register services
app = Flask(__name__)
app.register_blueprint(blueprint=api)        # 앞서 api.py에서 선언한 Blueprint 개체를 서비스로 등록
app.register_blueprint(blueprint=test)
app.register_blueprint(blueprint=dataset)

# Root
@app.route("/", methods=["GET"])
def index():
    return "<h1>hello world</h1>"

### Error Handler
import json
from werkzeug.exceptions import HTTPException
@app.errorhandler(HTTPException)
def handle_exception(e:HTTPException):
    """Return JSON instead of HTML for HTTP errors."""
    # start with the correct headers and status code from the error
    response = e.get_response()
    # replace the body with JSON
    response.data = json.dumps({
        "result": {},
        "status":{
            "code": e.code,
            "msg": e.name
        }
    })
    # e.description
    response.content_type = "application/json"
    return response

### Main
if __name__ == "__main__":
    serve(app, host="0.0.0.0", port=9090)
Comments