Django + Data
Django에서 데이터 사이언스 패키지 사용
- Django 기본 사용
- 웹 페이지 구성(template)
- 데이터 전달(View -> Template)
- 파이썬 BytesIO 패키지
View 에서 Template 으로 이미지 전달하기
- view에서 Template으로 이미지 형식의 데이터를 직접 전달할 수 없다.
- 저장된 이미지의 경로를 전달하여 Template에서 출력
- matplotlib의 그래프를 버퍼에 이미지 형식으로 저장 후 저장된 경로를 전달
- 버퍼(buffer): 임시로 데이터를 저장하는 공간
- Python "BytesIO" 클래스
- 파이썬의 내장 모듈인 "io" 모듈에 포함된 클래스
- 메모리 내에 데이터를 저장 및 조작할 수 있는 기능 제공
from django.shortcuts import render
import matplotlib.pyplot as plt
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')
buffer = BytesIO()
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>