如何在Django视图中返回HTML?

2024-04-20 04:21:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在浏览器上显示matlib绘图,我使用的是Django。到目前为止,我已经:

import matplotlib.pyplot as plt
import base64
from io import BytesIO

fig = plt.figure()
#plot sth

tmpfile = BytesIO()
fig.savefig(tmpfile, format='png')
encoded = base64.b64encode(tmpfile.getvalue())

html = 'Some html head' + '<img src=\'data:image/png;base64,{}\'>'.format(encoded) + 'Some more html'

with open('test.html','w') as f:
    f.write(html)

但是,我想要的不是f.write(html),而是:

return render_to_response(html)

如何处理一个大的html字符串?你知道吗


Tags: importformatpnghtmlasfig浏览器plt
2条回答

你试过HttpResponse吗?你知道吗

return HttpResponse("<p>Some html</p>")

我是用这个库得到的:https://mpld3.github.io/quickstart.html

fig = image_compare.get_images_figure()
html = mpld3.fig_to_html(fig)

return render(request, 'products/blank.html', {'html' : html})

以及空白.html看起来像这样:

{% autoescape off %}{{ html }}{% endautoescape %}

相关问题 更多 >