繁体   English   中英

使用 JQuery 表单提交成功后重新加载 flask 页面

[英]Reload flask page after form submission success with JQuery

我有一个页面使用带有 POST 方法的表单,该方法将文件传递给我的 flask 应用程序。 我读到我的app.route不能同时处理send_file和重定向。 所以我的解决方法是在post请求成功后刷新页面。

这是我的 HTML,我的脚本在底部:

    {% extends "base.html" %}
    {% block head %}
    <!-- {# <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/leaf.css') }}"> #} -->
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/base.css') }}"> -->
    {% endblock %}
    {% block content %}
    <div id="vo_budget_file_settings">
        {# <a href="/generatecleanbudgetfile" class="btn btn-primary">Upload Final CRO Budget File</a> #}
        <p>Please upload the final CRO budget File</p>
        <form class="" action="/generatecleanbudgetfile" method=POST enctype=multipart/form-data>
            <input type="file" name="data_file" accept=".xls, .xlsx, .xlsm"/>
            <input type="submit" value="Begin Format" onclick="loading();"/>
        </form>
    </div>
    <!-- funtion to show css spinner on button click -->
    <script type="text/javascript">
        function loading(){
          $(".loader").show();     
        }
        </script>
    <script type="text/javascript">
        // Reload page 60 seconds after form submission
        $("vo_budget_file_settings").onsubmit = setTimeout(function () {
            window.location = "/bugetformatter"; 
            }, 60000);
            console.log(window.location);
        </script>
    {% endblock %}

这是我的应用程序:

@app.route('/bugetformatter')
def data_request_portal():
    return render_template('CROBudgetFormatter.html', title='CRO Budget Formatting Tool')

@app.route('/generatecleanbudgetfile', methods=['GET', 'POST'])
def clean_budget():
    file = request.files.get('data_file')
    app.logger.info('Conversion has started')
    try:
        if request.method == 'POST':
            file = request.files.get('data_file')
            file.seek(0)
            buffer = budget_cleaner(file)
            buffer.seek(0)
            app.logger.info('Conversion Complete')
            return send_file(
            buffer,
            as_attachment=True,
            attachment_filename=f'stripped_budget_{dt.today().strftime("%m.%d.%Y")}.xlsx',
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
    except:
        return render_template('error_type.html', title='Unable to process uploaded budget.')

问题:

是否有一个脚本的行为类似于回调,并且只有在请求完成并且我的文件下载到浏览器后才会重新加载 window?

现在我正在使用 60 计时器在提交表单后重置,但我希望它与文件下载相关联,以防万一工作需要更长的时间。

您的应用需要

@app.route('/generatecleanbudgetfile', methods=['GET', 'POST'])
def clean_budget():
    file = request.files.get('data_file')
    app.logger.info('Conversion has started')
    try:
        if request.method == 'POST':
            file = request.files.get('data_file')
            file.seek(0)
            buffer = budget_cleaner(file)
            buffer.seek(0)
            app.logger.info('Conversion Complete')
            return send_file(
            buffer,
            as_attachment=True,
            attachment_filename=f'stripped_budget_{dt.today().strftime("%m.%d.%Y")}.xlsx',
            mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
            )
            return 1
    except:
        return render_template('error_type.html', title='Unable to process uploaded budget.')

并且您的 html 文件需要是:

    {% extends "base.html" %}
        {% block head %}
        <!-- {# <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/leaf.css') }}"> #} -->
        <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
        <!-- <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/base.css') }}"> -->
        {% endblock %}
        {% block content %}
        <div id="vo_budget_file_settings">
            {# <a href="/generatecleanbudgetfile" class="btn btn-primary">Upload Final CRO Budget File</a> #}
            <p>Please upload the final CRO budget File</p>
            <form class="formdata" action="/generatecleanbudgetfile" method=POST enctype=multipart/form-data>
                <input type="file" name="data_file" accept=".xls, .xlsx, .xlsm"/>
                <input type="button" value="Begin Format" onclick="submit();"/>
            </form>
        </div>
        <!-- funtion to show css spinner on button click -->
        <script type="text/javascript">
           $("form.formdata").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);  
               $.ajax({
                      type: "POST",
                      url: '/generatecleanbudgetfile',
                      data: formData,
                      cache: false,
                      contentType: false,
                      processData: false,
                      success: function(data) {
           window.location.reload();
        },
        error: function() {
            alert('Error occured');
            window.location.reload();
        }
        
       });     
      });
      </script>
      {% endblock %}

希望这对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM