1、将matplotlib生成的图片传输到前端
获得图像二进制
def getMat(saved_file):
data_08 = pd.read_csv(saved_file)
address_08 = data_08["TRADE_ADDRESS"].value_counts().sort_index()
import matplotlib.pyplot as plt
# 分析每个月份不同闸机的客流量分布
fig = plt.figure()
plt.title("address count per month")
plt.plot(address_08, color="g", label="08")
plt.legend()
plt.grid()
buffer = BytesIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()
return plot_data
传送到前端:
def csvtrain(request):
if request.method == 'GET':
return render(request, 'people.html')
else:
file = request.FILES.get('csv')
saved_path = os.path.join(settings.MEDIA_ROOT, 'user_photos')
if not os.path.exists(saved_path): # 如果文件路径不存在则创建文件保存目录
os.mkdir(saved_path)
saved_file = os.path.join(saved_path, '%s_%s.csv'%(datetime.datetime.now().day,datetime.datetime.now().minute)) # file.name为带后缀的文件名
with open(saved_file, 'wb+') as of: # 以二进制留写的方式写入文件,文件不存在则自动创建
if file.multiple_chunks(): # 判断如果文件大于默认值2.5M(可以修改)则采用分块的方式上传
for fc in file.chunks():
of.write(fc)
else:
of.write(file.read()) # 小于2.5M则直接上传
plot_data =getMat(saved_file)
imb = base64.b64encode(plot_data) # 对plot_data进行编码
ims = imb.decode()
imd = "data:image/png;base64," + ims
return render(request, 'people.html',{'img':imd})
html页面展示
<img src={{ img }}>