我正在尝试渲染一个可以在没有flask的情况下在我的计算机上运行的wordcloud。
路由
@app.route('/wordcloud/<vendor_duns>')
def images(vendor_duns):
words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all()
# t = [r.__dict__ for r in words]
# print(t)
one_row = list(itertools.chain.from_iterable(words))
text = ' '.join(one_row)
return render_template("wordcloud.html", text=text)
@app.route('/fig/<vendor_duns>')
def fig(vendor_duns):
# TODO add test model and query
words = Words.query.filter(Words.vendor_duns == vendor_duns).with_entities(Words.words).all()
one_row = list(itertools.chain.from_iterable(words))
text = ' '.join(one_row)
wordcloud = WordCloud().generate(text)
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
img = BytesIO()
plt.savefig(img)
img.seek(0)
return send_file(img, mimetype='image/png')模板
{% extends "base.html" %}
{% block title %}Wordcloud{% endblock %}
{% block content %}
{{text}}
<div>
<img src="{{ url_for('sam.fig', vendor_duns=vendor_duns) }}" alt="Image Placeholder" height="100">
</div>
{% endblock %}首先,模板中的{{text}}只是为了查看。如果我导航到一个特定的vendor_duns,我会得到一个很长的文本字符串,但没有图像。
那么有两个问题,我到底需要在哪里运行查询?在fig或图像function中。
第二个问题是,我得到了一个空白图像,所以我不确定如何将单词云写入缓冲区。
发布于 2018-05-10 07:24:23
wordcloud to_image方法创建了一个PIL对象,因此您所要做的就是调用PIL的save方法。
img = BytesIO()
wordcloud.to_image().save(img, 'PNG')
img.seek(0)https://stackoverflow.com/questions/50261578
复制相似问题