在Flask中保留信息

huangapple go评论66阅读模式
英文:

Information retaining in Flask

问题

我正在尝试同时显示两个不同 div 块的内容。但是,当我点击 "Show Text" 后,另一个 div 块的内容就会消失。(参见图像以供参考)

我希望它可以这样运行:如果我点击 "Analyze" 或 "Show Text" 中的任何一个,内容应分别保留。

后端代码:

@app.route('/predict', methods=['POST', 'GET'])
def predict():
    email = request.form.get('email', '')

    if request.method == 'POST':
        # ... 其他代码 ...

        return render_template('testing.html', prediction=my_prediction, percentage=percentage, result=count_of_words, email=email, emo_data=emo_data)

    return render_template('testing.html', email=email)

@app.route('/highlight_text', methods=['POST'])
def highlight_text():
    email = request.form.get('email', '')

    if not email:
        return render_template('testing.html', error_message='Please enter an email.', email=email)

    # ... 其他代码 ...

    return render_template('testing.html', highlighted_text=highlighted_text, email=email, prediction=prediction, percentage=percentage, result=result, emo_data=emo_data)

前端代码:

<div class="right-element">
    {% if prediction is defined %}
    <div class="result box">
        <h5>Prediction {% if prediction == 1 %}<span style="color: red;">Spam</span>{% elif prediction == 0 %}
            <span style="color: green;">Not Spam</span>{% endif %}</h5>
        <h5>Spam Probability {{ percentage }} %</h5>
        <h5>Word Count {{ result }}</h5>
        <br>
        <h5>Emotional Analysis:</h5>
        <table class="table">
            <thead>
                <tr>
                    <th>Emotion Label</th>
                    <th>Score</th>
                </tr>
            </thead>
            <tbody>
                {% for label, score in emo_data %}
                <tr>
                    <td>{{ label }}</td>
                    <td>{{ score }}%</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    {% endif %}
</div>

<div class="highlighted-text">
    <h3>Highlighted text for Emotions</h3>
    <p>{{ highlighted_text | safe }}</p>

    <form action="{{ url_for('highlight_text') }}" method="post" id="highlight-form">
        <input type="hidden" name="email" value="{{ email }}">
        <button type="submit" id="highlight-btn" name="highlight-btn">Show Text</button>
    </form>
</div>

Images:
在Flask中保留信息
在Flask中保留信息


<details>
<summary>英文:</summary>

I&#39;m trying to display both the contents of two different div blocks. But after I click on &quot;Show Text&quot; the other div block content disappears. (See images for reference)

I want to make it function such that if I click on either &#39;Analyze&#39; or &#39;Show Text&#39;, the contain must be retained for either of the two respectively.

Backend code:

    @app.route(&#39;/predict&#39;, methods=[&#39;POST&#39;, &#39;GET&#39;])
    def predict():
        email = request.form.get(&#39;email&#39;, &#39;&#39;)
        
        if request.method == &#39;POST&#39;:
            if not email:
                return render_template(&#39;testing.html&#39;, error_message=&#39;Please enter an email.&#39;, email=email)
            else:
                count_of_words = len(email.split())
    
                # Perform Emotional Analysis
                result = emotion(email)  # Emotional Analysis Labels
                sorted_labels = sort_emo(result)  # Sorting in Descending order; extracts top 5 labels
    
                # Clean the text
                clean_text = clean_html(email)
                processed_text = clean_string(clean_text)
    
                # Perform Spam Detection prediction
                string_vectorized = vectorizer.transform([processed_text])
                my_prediction = model.predict(string_vectorized)
                probability = model.predict_proba(string_vectorized)[0][1]
                percentage = round(probability * 100, 2)
    
                # Capitalize emotion labels
                capitalized_labels = []
                scores = []
    
                # For extracting top 5 labels
                for res in sorted_labels:
                    label = res[&#39;label&#39;]
                    capitalized_label = label.capitalize()
                    score = round(res[&#39;score&#39;] * 100, 2)
                    capitalized_labels.append(capitalized_label)
                    scores.append(score)
    
                # Zipping the lists together
                emo_data = zip(capitalized_labels, scores)
                
                return render_template(&#39;testing.html&#39;, prediction=my_prediction, percentage=percentage, result=count_of_words, email=email, emo_data=emo_data)
    
        # For GET request or if no form submission has occurred
        return render_template(&#39;testing.html&#39;, email=email)
    
    @app.route(&#39;/highlight_text&#39;, methods=[&#39;POST&#39;])
    def highlight_text():
        email = request.form.get(&#39;email&#39;, &#39;&#39;)
    
        if not email:
            return render_template(&#39;testing.html&#39;, error_message=&#39;Please enter an email.&#39;, email=email)
    
        # Perform necessary processing to generate highlighted text
        processed_text = clean_string(clean_html(email))
        emotion_lists = process_text_emotions(processed_text)
        reduced_emotions = create_reduced_emotions(emotion_lists)
        highlighted_text = generate_html_with_highlights(email, reduced_emotions)
    
        # Fetch the relevant variables for rendering the template
        prediction = request.form.get(&#39;prediction&#39;)
        percentage = request.form.get(&#39;percentage&#39;)
        result = request.form.get(&#39;result&#39;)
        emo_data = request.form.getlist(&#39;emo_data&#39;)
    
        return render_template(&#39;testing.html&#39;, highlighted_text=highlighted_text, email=email, prediction=prediction, percentage=percentage, result=result, emo_data=emo_data)

Frontend:

    &lt;div class=&quot;right-element&quot;&gt;
        {% if prediction is defined %}
        &lt;div class=&quot;result box&quot;&gt;
            &lt;h5&gt;Prediction {% if prediction == 1 %}&lt;span style=&quot;color: red;&quot;&gt;Spam&lt;/span&gt;{% elif prediction == 0 %}
                &lt;span style=&quot;color: green;&quot;&gt;Not Spam&lt;/span&gt;{% endif %}&lt;/h5&gt;
            &lt;h5&gt;Spam Probability {{ percentage }} %&lt;/h5&gt;
            &lt;h5&gt;Word Count {{ result }}&lt;/h5&gt;
            &lt;br&gt;
            &lt;h5&gt;Emotional Analysis:&lt;/h5&gt;
            &lt;table class=&quot;table&quot;&gt;
                &lt;thead&gt;
                    &lt;tr&gt;
                        &lt;th&gt;Emotion Label&lt;/th&gt;
                        &lt;th&gt;Score&lt;/th&gt;
                    &lt;/tr&gt;
                &lt;/thead&gt;
                &lt;tbody&gt;
                    {% for label, score in emo_data %}
                    &lt;tr&gt;
                        &lt;td&gt;{{ label }}&lt;/td&gt;
                        &lt;td&gt;{{ score }}%&lt;/td&gt;
                    &lt;/tr&gt;
                    {% endfor %}
                &lt;/tbody&gt;
            &lt;/table&gt;
        &lt;/div&gt;
        {% endif %}
    &lt;/div&gt;
	
	        &lt;div class=&quot;highlighted-text&quot;&gt;
        &lt;h3&gt;Highlighted text for Emotions&lt;/h3&gt;
        &lt;p&gt;{{ highlighted_text | safe }}&lt;/p&gt;
    
        &lt;form action=&quot;{{ url_for(&#39;highlight_text&#39;) }}&quot; method=&quot;post&quot; id=&quot;highlight-form&quot;&gt;
            &lt;input type=&quot;hidden&quot; name=&quot;email&quot; value=&quot;{{ email }}&quot;&gt;
            &lt;button type=&quot;submit&quot; id=&quot;highlight-btn&quot; name=&quot;highlight-btn&quot;&gt;Show Text&lt;/button&gt;
        &lt;/form&gt;
    &lt;/div&gt;

Images:
[![When Analyze is clicked][1]][1]
[![When Show Text is clicked][2]][2]


  [1]: https://i.stack.imgur.com/XYGDB.png
  [2]: https://i.stack.imgur.com/Cw46d.png

</details>


# 答案1
**得分**: 1

1. ```Show Text``` 提交您的表单。

2. 该表单中唯一的字段是一个用于电子邮件的隐藏字段。表单不包含```percentage, result```字段,这意味着以下行将返回```None```。

```python
    prediction = request.form.get('prediction')
    percentage = request.form.get('percentage')
  1. 要实现您的要求,您需要将percentage, result也放在表单中,或者保持您的设计不变,通过Javascript和Ajax调用提交您的表单。如果您进行Ajax调用,这意味着您的HTML页面不会被重新加载。然后,您可以简单地将通过Javascript和Ajax调用完成的表单调用的结果附加到您想要的位置。在Stackoverflow上进行快速搜索将向您展示如何通过Javascript和Ajax调用提交表单。
英文:
  1. Show Text submits your form.

  2. The only field in that form is a hidden field for email. The form doesn't contain the fields for percentage, result which means that the following lines will return None

    prediction = request.form.get(&#39;prediction&#39;)
    percentage = request.form.get(&#39;percentage&#39;)
  1. To achieve your requirement, you need to place percentage, result in the form too or keep your design as is, and submit your form via Javascript and Ajax call. If you do an Ajax call, it means your html page won't be reloaded. You can then simply append the result of the form call (the one you did via Javascript and Ajax) to the places you want. A quick search on Stackoverflow will show you how to submit a form via Javascript and Ajax call

huangapple
  • 本文由 发表于 2023年7月12日 20:37:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/76670630.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定