简体   繁体   中英

Return call to a Flask API call as JSON in HTML

I am new to flask, and am using it to develop an API. In my current implementation, I have a function that returns a list of values.

def search(query):
    # do stuff with query to convert it into a list of 
    # restaurants and ratings
    name_rating_pairs = [{'chipotle':4.3},{'arbys':4.2}]

How do I display these values on an HTML page of my app?

I've had great success with simple ajax on my flask sites, running an asynchronous query on a form submission, and populate an element with the json results.

On the python side, you can do the following:

from flask import Flask, request, render_template, jsonify
app = Flask(__name__)

def search(query):
    # do stuff with query to convert it into a list of 
    # restaurants and ratings
    name_rating_pairs = [{'chipotle':4.3},{'arbys':4.2}]
    return name_rating_pairs

@app.route('/run_query')
def api_sleuth():
    query = request.args.get('query', '', type=str)
    ret = None if query == '' else jsonify(search(query))
    return ret


@app.route('/')
@app.route('/index', methods=['GET'])
def index():
    return render_template('index.html')

And on the html side (though you'd want the head and body elements to be in a separate template):

<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>My Flask App</title></head>

<body>
  <!-- setup ajax -->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"> 
  </script>
  <script>window.jQuery || document.write('<script src="{{url_for('static', filename = 'jquery.js') }}">\x3C/script>')</script>
  <script type=text/javascript>
      $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
    </script>

  <!-- your app -->
  <div id="container">
    <script type=text/javascript>
      $(function() {
        $('a#calculate').bind('click', function() {
          if ($('input[name="query"]').val().length > 0) {
            $("#running").text('Running...');
            $.getJSON($SCRIPT_ROOT + '/run_query', {
              query: $('input[name="query"]').val(),
            }, function(data) {
              $("#output").text(JSON.stringify(data, null, 2));
            });
          }
          return false;
        });
      });
    </script>
    <h1>What do you want to know?</h1>
    <p>
      <input type=text name=query>
      <a href=# id=calculate>Run!</a>
    </p>
      <p><span id=running></span></p>
    <pre id=output>Full output</pre>
  </div>
</body>
</html>

Of course, you can format the json differently than dumping it to a pre element, but that is a good way to simply display it in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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