Python을 배워보자

국가별 월별 기온 데이터를 FastAPI로 백엔드 구축 및 Dash로 테이블 출력하기

_Blue_Sky_ 2025. 7. 24. 13:44
728x90

소개

안녕하세요! 오늘은 Python을 활용해 국가별 월별 기온 데이터를 동적으로 처리하고 웹 기반 GUI로 표시하는 방법을 다뤄보겠습니다. 이전에 Flask를 사용한 예제를 FastAPI로 업그레이드하며, Dash를 통해 상호 인터랙티브한 테이블을 구현합니다. FastAPI는 높은 성능과 비동기 처리로 유명하니, 이를 통해 더 효율적인 서버를 경험해 볼 수 있습니다. 

 

728x90

1. FastAPI로 백엔드 구축

FastAPI를 사용해 더미 데이터를 제공하는 REST API를 만듭니다. 실제로는 기상청 API를 연동할 수 있지만, 여기서는 간단히 시뮬레이션합니다. 파일은 backend.py로 저장하세요.

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

# CORS 설정 (Dash와 통신을 위해 필요)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 모든 출처 허용 (개발용, 배포 시 제한 권장)
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 더미 데이터
temperature_data = {
    "South Korea": {"Jan": -2.5, "Feb": 0.5, "Mar": 5.8, "Apr": 12.3, "May": 18.2, "Jun": 22.5, "Jul": 25.8, "Aug": 26.5, "Sep": 21.7, "Oct": 15.1, "Nov": 7.2, "Dec": 0.1},
    "Japan": {"Jan": 5.0, "Feb": 6.2, "Mar": 9.8, "Apr": 15.5, "May": 20.1, "Jun": 24.3, "Jul": 27.6, "Aug": 28.2, "Sep": 23.9, "Oct": 18.4, "Nov": 12.6, "Dec": 7.8},
    "USA": {"Jan": -1.0, "Feb": 1.5, "Mar": 6.7, "Apr": 13.9, "May": 19.8, "Jun": 24.1, "Jul": 27.3, "Aug": 26.9, "Sep": 22.5, "Oct": 16.2, "Nov": 8.9, "Dec": 2.1}
}

@app.get("/api/temperatures")
async def get_temperatures():
    return temperature_data
  • 설명: FastAPI는 비동기 처리(async/await)를 지원하며, CORS 설정으로 Dash와의 통신을 원활히 합니다. 더미 데이터는 3개 국가의 월별 평균 기온을 포함합니다.

2. Dash로 프론트엔드 구현

FastAPI에서 데이터를 가져와 Dash로 테이블을 동적으로 렌더링합니다. 파일은 dashboard.py로 저장하세요.

from dash import Dash, html, dcc, Output, Input
import dash_table
import requests

# Dash 앱 초기화
app = Dash(__name__)

# 레이아웃 정의
app.layout = html.Div([
    html.H1("국가별 월별 평균 기온", style={'textAlign': 'center'}),

    # 데이터 테이블
    dash_table.DataTable(
        id='temperature-table',
        columns=[
            {"name": "Country", "id": "country"},
            {"name": "Jan", "id": "Jan", "type": "numeric"},
            {"name": "Feb", "id": "Feb", "type": "numeric"},
            {"name": "Mar", "id": "Mar", "type": "numeric"},
            {"name": "Apr", "id": "Apr", "type": "numeric"},
            {"name": "May", "id": "May", "type": "numeric"},
            {"name": "Jun", "id": "Jun", "type": "numeric"},
            {"name": "Jul", "id": "Jul", "type": "numeric"},
            {"name": "Aug", "id": "Aug", "type": "numeric"},
            {"name": "Sep", "id": "Sep", "type": "numeric"},
            {"name": "Oct", "id": "Oct", "type": "numeric"},
            {"name": "Nov", "id": "Nov", "type": "numeric"},
            {"name": "Dec", "id": "Dec", "type": "numeric"}
        ],
        data=[],
        style_table={'overflowX': 'auto'},
        style_cell={'textAlign': 'center', 'padding': '5px'},
        style_header={'backgroundColor': 'lightgrey', 'fontWeight': 'bold'}
    ),

    # 데이터 갱신 버튼
    html.Button('데이터 갱신', id='refresh-button', n_clicks=0),
])

# 콜백 함수: 데이터 동적 로드
@app.callback(
    Output('temperature-table', 'data'),
    Input('refresh-button', 'n_clicks')
)
def update_table(n_clicks):
    if n_clicks > 0:
        # FastAPI 백엔드에서 데이터 가져오기
        response = requests.get('http://localhost:5000/api/temperatures')
        if response.status_code == 200:
            data = response.json()
            table_data = []
            for country, months in data.items():
                row = {"country": country}
                row.update(months)
                table_data.append(row)
            return table_data
    return []

# 앱 실행
if __name__ == '__main__':
    app.run_server(debug=True, port=8050)
  • 설명: FastAPI 서버(http://localhost:5000)에서 데이터를 가져와 Dash 테이블에 반영합니다. 버튼 클릭 시 데이터가 갱신되며, 테이블은 국가별 월별 기온을 시각화합니다.

 

728x90

3. 실행 방법 (macOS)

  1. 의존성 설치:
    • 터미널에서 다음 명령어 실행: 
    • pip install fastapi uvicorn dash requests
  2. 백엔드 실행:
    • backend.py 디렉토리로 이동 후:
      uvicorn backend:app --reload --port 5000
    • 서버가 http://localhost:5000에서 실행됨.
  3. 프론트엔드 실행:
    • 별도 터미널에서 dashboard.py 디렉토리로 이동 후:
      python dashboard.py
    • 브라우저가 http://127.0.0.1:8050에서 열림.

4. 동작 확인

  • 초기에는 테이블이 비어 있음.
  • "데이터 갱신" 버튼을 누르면 South Korea, Japan, USA의 월별 기온 데이터가 테이블에 표시됨 (예: July의 South Korea 기온은 25.8°C).

5. 실제 API 연동 (참고)

  • 기상청 개방포털: data.kma.go.kr에서 API 키를 발급받아 FastAPI에서 연동 가능. 예:
    response = requests.get('http://apis.data.go.kr/1360000/AsosDalyInfoService/getWthrDataList', params={
        'serviceKey': 'YOUR_API_KEY',
        'pageNo': '1',
        'numOfRows': '10',
        'dataType': 'JSON',
        'dateCd': 'MONTH',
        'startDt': '202401',
        'endDt': '202412',
        'stnIds': '108'
    })
  • 응답 데이터를 temperature_data에 반영.

6. 추가 개선

  • 실시간 갱신: dcc.Interval로 주기적 데이터 호출 추가.
  • 오류 처리: 네트워크 오류 시 사용자 알림 구현.
  • 스타일링: CSS로 테이블 디자인 개선.

마무리

FastAPI와 Dash를 활용하면 고성능 백엔드와 동적인 웹 GUI를 쉽게 구현할 수 있습니다. 더 많은 국가 데이터나 그래프 추가를 원하시면 말씀해 주세요. 즐거운 코딩 되세요!

728x90