Villuck
Villuck

Reputation: 61

How to return also json and render_template in Flask?

I've implemented a service in Python with Flask, to create the server. My service (MyService) take a query from the user and return a response, like a chatbot. So, i want to return both a text respons modifying the Html template, and a json containing response for using service as command line. At the moment my service only return a render template,how I can do?

My app:

app = Flask(__name__)

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

@app.route("/result", methods=['POST', 'GET'])
def result():
   if request.method == 'POST':
       query = request.form['query']
       response = MyService.retrieve_response(query)
       return render_template("index.html", value=response)

if __name__ == "__main__":
    app.run()

And my simple index.html:

<!DOCTYPE html>
<html lang="en">

<body>

<h2>Wellcome!</h2>

<form action="http://localhost:5000/result" method="POST">
  Make a question:<br>
  <br>
  <input type="text" name="query" id="query">
  <br><br>
  <input type="submit" value="submit"/>
</form>


<br>
<h3>Response is: </h3>
<br>
{{value}}
</body>
</html>

Upvotes: 6

Views: 15962

Answers (2)

fearless_fool
fearless_fool

Reputation: 35169

@dvnguyen's answer is good, but you might consider creating different routes for html and for json. For example:

@app.route("/web/result")
def result_html():
   response = MyService.retrieve_response()
   return render_template("index.html", value=response)

@app.route("/api/result")
def result_json():
   response = MyService.retrieve_response()
   return jsonify(response)

The /api or /web prefix makes the intention clear, and also simplifies unit testing.

Upvotes: 7

dvnguyen
dvnguyen

Reputation: 3022

You can branch out your return based on request type. If the request is for html text, return the render_template. If the request is for json, return json. For example:

@app.route("/result", methods=['POST', 'GET'])
def result():
   if request.method == 'POST':
       query = request.form['query']
       response = MyService.retrieve_response(query)
       if request.headers['Content-Type'] == 'application/json':
           return jsonify(...)
       return render_template("index.html", value=response)

Upvotes: 8

Related Questions