Elizabeth
Elizabeth

Reputation: 282

python flask with json

I am trying to get user's input and return the details as json. But I get an error and I can't find why. Hers is my python code:

from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')


@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    dictionaryToJson = json.dumps(pythonDictionary)
    return jsonify(dictionaryToJson)

and my HTML file:

<html>
   <body>

      <form action = "http://localhost:5000/result" method = "POST">
         <p>Book Name <input type = "text" name = "Book_Name" /></p>
         <p>Page <input type = "text" name = "Page" /></p>
         <p>Text <input type = "text" name = "Text" /></p>
         <p>Topic <input type ="text" name = "Topic" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>

   </body>
</html>

How can I return the values properly?

Upvotes: 0

Views: 312

Answers (2)

Artsiom Praneuski
Artsiom Praneuski

Reputation: 2329

0) Do not use uppercase for vars. Uppercase is always for constants.

1) Use routes with "/" at the end to avoid additional redirects which flask does:

@app.route('/user_input/', methods = ['POST'])

2) Use the same route and the same function to get what you need:

from flask import Flask, request, render_template, jsonify


def json_response(status_code, data):
    res = jsonify(data)
    res.status_code = status_code
    return res

app = Flask(__name__)


@app.route('/user_input/', methods=["GET", "POST"])
def user_input():
    if request.method == "GET":
        return render_template('user-input.html')
    else:
        python_dictionary = {'bookName': request.form.get('Book_Name'),
                             'page': request.form.get('Page'),
                             'text': request.form.get('Text'),
                             'topic': request.form.get('Topic')}
        return json_response(200, python_dictionary)

app.run()

3) And yes, you don't need to use json.dumps(pythonDictionary) before passing dictionary to jsonify

4) Consider to use request.form.get('key') rather than request.form['key'] because get() function returns None if there is no such key:value instead of raising key error exception.

Upvotes: 1

alexisdevarennes
alexisdevarennes

Reputation: 5642

You are dumping the dict twice as jsonify also does json.dumps() (it also sets the correct response headers for you in addition which is why you should use it instead of json.dumps():

dictionaryToJson = json.dumps(pythonDictionary)
return jsonify(dictionaryToJson)

Do this:

from flask import Flask, request, render_template,jsonify
import json
@app.route('/user_input')
def user_input():
    return render_template('user-input.html')


@app.route('/user_input',methods = ['POST'])
def result():
    NAME = request.form['Book_Name']
    PAGE = request.form['Page']
    TEXT = request.form['Text']
    TOPIC = request.form['Topic']
    pythonDictionary = {'bookName': NAME, 'page': PAGE, 'text': TEXT, 'topic': TOPIC}
    return jsonify(pythonDictionary )

Upvotes: 1

Related Questions