Home > database >  How to select Results from Post request and print them to file in Flask?
How to select Results from Post request and print them to file in Flask?

Time:02-04

I have been trying to make a post request return some data in checkboxes and then use these checkbox selection to write to a file. I am using an API call to return some application data and I want to be able to select only specific applications and write these to a file. The way I have this setup now is that my second POST request return a 404.

    @app.route("/Application", methods=['POST'])
    @app.route("/Application")
    def get_system_app_data():
        operating_app_sys = None
        form = ApplicationForm()

        api_call = aggregation.api(something)

        if form.validate_on_submit():
            operating_app_sys = form.operating_app_sys.data

        if request.method == 'POST':
            applications = (
                    api_call.get_systems_running_app(operating_app_sys))
                    
            # with open('file.txt', 'w') as f:
            #     f.write(request.form.getlist('mycheck'))
                
            return render_template('application.html', form=form, applications=applications)

My HTML code:

<form method="POST" action="">
  {{ form.hidden_tag() }}

  {{ form.operating_app_sys.label() }}
  {{ form.operating_app_sys() }}
  </br>
  {{ form.submit() }}
</form>
</br>
</form>
</div>
</br>

<body>
  <form method="POST" action="">
    {%- for customer in applications %}
      {%- if customer.get("name", {}) == "1" %}
        {%- for team in customer.get("app_name") %}
          {{ team.get('app_name') }}<input type ="checkbox" value="1" name="mycheck">
        {%- endfor %}
      {%- endif %}
    {%- endfor %}
    <input type="submit" name="btn" value="some">         
  </form>
</body>

CodePudding user response:

The solution was to get the search term and redirect to another route:

@app.route("/Application", methods=['POST'])
@app.route("/Application")
def get_system_app_data():
    operating_app_sys = None
    form = ApplicationForm()

    if form.validate_on_submit():
        operating_app_sys = form.operating_app_sys.data

    if request.method == 'POST':
        search = request.form["operating_app_sys"]

        return redirect(url_for('get_results', search=search))

Then:

@app.route("/Results", methods=['GET', 'POST'])
@app.route("/Results")
def get_results():
    form = ApplicationForm()
    search = request.args.get('search', None)
    api_call = aggregation.api(search)


    if request.method == 'POST':
        print(request.form.getlist('mycheck'))
  • Related