Similar questions have been asked but I can't get it to work for me, I'm not sure what the issue is so I thought I'd ask again incase anyone has some pointers.
I am trying to pass a function in Flask dependent on which button is pressed on the webpage. These are the HTML buttons:
<div class="row">
<h2>Your Wordclouds:</h2>
<input type="submit" name="submit_button" value="Positive" class='btn'>
<input type="submit" name="submit_button" value="Negative" class='btn'>
{{value}}
</div>
My function:
@app.route('/insight', methods=['GET', 'POST'])
def wordcloud():
if request.method == 'POST':
if request.form['submit_button'] == "Positive":
mysql.connection.cursor()
query = ("SELECT journal_entry FROM journals WHERE sentiment = 'positive'")
df = pd.read_sql(query, mysql.connection)
journal_entry = df['journal_entry']
long_string = (''.join(str(journal_entry.tolist())))
# Create WordCloud object
wordcloud = WordCloud(background_color="white", max_words=4500, contour_width=6, contour_color='blue')
# Generate the cloud
wordcloud.generate(long_string)
wordcloud.to_file("wordcloud.png")
filename = Image.open("wordcloud.png")
main_themes = filename.show()
elif request.form['submit_button'] == "Negative":
mysql.connection.cursor()
query = ("SELECT journal_entry FROM journals WHERE sentiment = 'negative'")
df = pd.read_sql(query, mysql.connection)
journal_entry = df['journal_entry']
long_string = (''.join(str(journal_entry.tolist())))
# Create WordCloud object
wordcloud = WordCloud(background_color="white", max_words=500, contour_width=6, contour_color='blue')
# Generate the cloud
wordcloud.generate(long_string)
wordcloud.to_file("wordcloud.png")
filename = Image.open("wordcloud.png")
main_themes = filename.show()
return render_template('insight.html', value=main_themes)
else:
return render_template('insight.html')
The functions work fine individually when I use the GET method, and the wordcloud image is automatically generated on page load. But since there are options I only want to trigger the generation on click.
Any help much appreciated