如何防止 Flask 应用程序中页面重新加载时弹出确认重新提交?

问题描述 投票:0回答:1

简介

我正在开发一个 Flask 应用程序,用户可以通过表单提交反馈。提交表单后,我想将用户重定向到主页,而不是在重新加载页面时显示确认重新提交弹出窗口。

问题

我遇到以下问题:

  • 当我在提交表单后重新加载页面时,会出现确认重新提交弹出窗口。
  • 我想确保用户被重定向到主页而不是看到这个弹出窗口。
  • 此外,我想实现反馈按钮(拇指向上和拇指向下),直观地指示选择了哪个按钮。”

代码片段

这是我的

app.py
文件中的相关代码:

@app.route("/",methods=['get', 'post'])
def index():
 form = userinput()
 if request.method == 'POST':
   connect = apiurl
   resp = requests.post(connect)
   url = resp.json()['url']
   message = resp.json()['text']
   return render_template(home.html, title = 'index', form=form, url=url, message=message)
return render_template(index.html, form=form)

forms.py

class UserInput(FlaskForm):
    text = TextAreaField('Enter your Question ', validators=[DataRequired()])
    submit = SubmitField('Request for the Answer')
    feedback = StringField('Feedback')

index.html

{% extends "layout.html" %}
{% block content %}
<!--    <h1>Home Page</h1>-->
<!--    <span>Request Method - {{ request_method }}</span>-->
{% endblock content %}

这是

home.html
中的反馈按钮实现:

{% extends "layout.html" %}
{% block content %}
        <ul class = "label-for-list"> Files:
            <li class="list"><a href="{{ url }}">{{ url }}</a></li>
        </ul>
        <div class ="second">
            <label for="exampleFormControlTextarea1" class="form-label">Answer: </label>
            <textarea class="form-control" id="exampleFormControlTextarea1" rows="12">{{ message }}</textarea>
        </div>
        <div class="feedback-button">
            {{ form.feedback.label(class="form-label") }}
            <input type="button" value="👍" class="emoticon" title="thumbs-up" onclick="console.log('Positive')" onmousedown="mousedown()" onmouseup="mouseup()">
            <input type="button" value="👎" class="emoticon" title="thumbs-down" onclick="console.log('Negative')">
        </div>
        <script>
            function mousedown(input){
                input.style.color = "blue";
            }
        </script>

{% endblock content %}

布局.html

<div class="container">
        <div class="content-section">
        <form method="POST" action="/">
            {{ form.hidden_tag() }}
            <fieldset class="form-group">
                <div class="form-group">
                    {{ form.text.label(class="form-control-label") }}
                    {{ form.text(class="form-control form-control-lg",rows="5") }}
                </div>
            </fieldset>
            <div class="form-group d-grid gap-2">
                {{ form.submit(class="btn btn-outline-info") }}
            </div>
            {% block content %}{% endblock %}
        </form>
        </div>
    </div>

api.py

from flask import Flask, request, jsonify
from flask_cors import CORS
from wonderwords import RandomSentence
import random

app = Flask(__name__)
CORS(app)


@app.route('/', methods=['GET', 'POST'])
def func():
    print(request.method)
    if(request.method == 'GET'):
        response = "This is just GET request and API is up and running"
        return jsonify({'response': response})

    elif(request.method == 'POST'):
        data = request.data.decode('utf-8')
        url = f"https:\\SourceDir\\file{random.randint(0,10)}.pdf"
        s = RandomSentence()
        # d = {"text":data.strip('\"'),'URL':url}
        d = {"text": s.sentence(), "URL": url}
        return d


if __name__ == '__main__':
    # app.run(debug=True)
    app.run(host="0.0.0.0", port=8000)

问题

  1. 如何防止表单提交后重新加载页面时出现确认重新提交弹窗?
  2. 实现直观地指示选择了哪个按钮的反馈按钮的最佳方法是什么?

我将不胜感激任何可以帮助我有效解决这些问题的见解或例子。谢谢你!”

python html flask
1个回答
1
投票

我假设您想要一种在人们单击您的反馈按钮后重定向人们的方法,您只需使用

index
函数修改您的
redirect
函数即可。我假设您有一个
home
函数,就像您的
index
函数

一样
from flask import Flask, render_template, request, redirect, url_for

@app.route("/", methods=['GET', 'POST'])
def index():
    form = UserInput()
    if request.method == 'POST':
        connect = apiurl
        resp = requests.post(connect)
        url = resp.json()['url']
        message = resp.json()['text']
        # added a redirect function
        return redirect(url_for('index', url=url, message=message))
    return render_template('index.html', form=form)

还需要在

JS
中编写脚本,通过获取按钮的
id
来监听点击等事件。

 <script>
   function sendFeedback(action) {
      const thumbsUp = document.getElementById('thumbsup');
      const thumbsDown = document.getElementById('thumbsdown');
            
      if (action === 'up') {
        // change the colour when a up button is clicked
           thumbsUp.style.backgroundColor = 'blue';
            thumbsDown.style.backgroundColor = '';
     } if (action === 'down') {
           // change the colour when a down button is clicked
            thumbsDown.style.backgroundColor = 'blue';
            thumbsUp.style.backgroundColor = '';
          }
      }
 </script>

将该函数添加到您的 html 文件中

<div class="feedback-button">
    <input type="button" value="👍" class="emoticon" id="thumbsup" title="thumbs-up" onclick="sendFeedback('up')">
    <input type="button" value="👎" class="emoticon" id="thumbsdown" title="thumbs-down" onclick="sendFeedback('down')">
</div>
© www.soinside.com 2019 - 2024. All rights reserved.