Django + Data

Jingi·2024년 4월 5일

Web

목록 보기
19/40
post-thumbnail

Django + Data

Django에서 데이터 사이언스 패키지 사용

  • Django 기본 사용
    • 웹 페이지 구성(template)
    • 데이터 전달(View -> Template)
  • 파이썬 BytesIO 패키지

View 에서 Template 으로 이미지 전달하기

  • view에서 Template으로 이미지 형식의 데이터를 직접 전달할 수 없다.
  • 저장된 이미지의 경로를 전달하여 Template에서 출력
  • matplotlib의 그래프를 버퍼에 이미지 형식으로 저장 후 저장된 경로를 전달
    • 버퍼(buffer): 임시로 데이터를 저장하는 공간
  • Python "BytesIO" 클래스
    • 파이썬의 내장 모듈인 "io" 모듈에 포함된 클래스
    • 메모리 내에 데이터를 저장 및 조작할 수 있는 기능 제공
# myapps/vies.py

from django.shortcuts import render
import matplotlib.pyplot as plt

# io : 입출력 연산을 위한 Python 표준 라이브러리

# BytesIO : 이진 데이터를 다루기 위한 버퍼를 제공
from io import BytesIO

# 텍스트 <=> 이진 데이터를 변환할 수 있는 모듈
import base64

def index(request):
    x = [1,2,3,4]
    y = [2,4,6,8]
    plt.plot(x, y)
    plt.title("text graph")
    plt.xlabel('x label')
    plt.ylabel('y label')
    
    # 새창이 통채로 열린다
    # plt.show()
    
    # 비어있는 버퍼 생성
    buffer = BytesIO()
    
    # buffer에 그래프를 png 형태로 저장
    plt.savefig(buffer, format='png')
    
    # 버퍼의 내용을 인코딩
    img_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8').replace('\n','')
    buffer.close()
    
    context = {
        'chart_image' : f'data:image/png;base64,{img_base64}',
    }
    return render(request, "index.html", context)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Django Tempalte 에서 그래프 출력</h1>
    <img src="{{ chart_image }}" alt="">
</body>
</html>
profile
데이터 분석에서 백엔드까지...

0개의 댓글