Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all POST variables from form from python controller [duplicate]

NOTE: I have no idea how the other post sited answers this question. I did discover the following:

if you want to print to the browser you can just add:

return jsonify(request.form)

if you want to print to the console you can add:

my_data = request.form
for key in my_data:
    print ('form key '+key+" "+my_data[key])
return render_template("some.html")

I'm trying to print all POST variables with the following controller:

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/register", methods=["POST"])
def register():  

dict = request.form
for key in dict:
    print ('form key '+dict[key])

but am getting the error:

ValueError: View function did not return a response

here is my form:

{% extends "layout.html" %}

{% block title %}
Frosh IMs
{% endblock %}

{% block body %}
<h1>Register for Frosh IMs</h1>
<form action="{{ url_for('register') }}" method="post">
    Name: <input name="name" type="text"/>
    <br/>
    Dorm:
    <select name="dorm">
      <option value=""></option>
      <option value="Apley Court">Apley Court</option>
      <option value="Canaday">Canaday</option>
      <option value="Grays">Grays</option>
      <option value="Greenough">Greenough</option>
      <option value="Hollis">Hollis</option>
      <option value="Holworthy">Holworthy</option>
      <option value="Hurlbut">Hurlbut</option>
      <option value="Lionel">Lionel</option>
      <option value="Matthews">Matthews</option>
      <option value="Mower">Mower</option>
      <option value="Pennypacker">Pennypacker</option>
      <option value="Stoughton">Stoughton</option>
      <option value="Straus">Straus</option>
      <option value="Thayer">Thayer</option>
      <option value="Weld">Weld</option>
      <option value="Wigglesworth">Wigglesworth</option>
    </select>
    <br/>
    <input type="submit" value="Register"/>
</form>
{% endblock %}
like image 822
DCR Avatar asked Jul 04 '26 10:07

DCR


1 Answers

you need flask to return something to the browser:

from flask import jsonify

@app.route("/register", methods=["POST"])
def register():
    # this line goes to the console/terminal in flask dev server
    print request.form
    # this line prints out the form to the browser
    return jsonify(request.form.to_dict())

Multidict to_dict() method returns a normal python dict from the MultiDict.

like image 190
abigperson Avatar answered Jul 07 '26 02:07

abigperson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!