我是烧瓶新手。我正在使用它在API上工作。我得到了准确的答复和所有信息。我从JSON对象中提取了必要的值,并将它们存储在列表中。现在如何在我的应用程序的HTML页面上显示这些值而不将这些值存储在数据库中?
def search(query):
ent_type, ent_id, lat, lon = location(query, headers)
# print(restaurants_len)
start = 0
...
...
...
...
...
while i < restaurants_len:
name = response_dict['restaurants'][i]['restaurant']['name']
rating = response_dict['restaurants'][i]['restaurant']['user_rating']['aggregate_rating']
name_rating_pair.append((name, rating))
如您所见,我提取了这些值并将它们放在列表中。如何在HTML页面上显示这些值?
我在烧瓶站点上使用简单的ajax取得了巨大的成功,在表单提交上运行了异步查询,并使用json结果填充了一个元素。
旁注,您可能仍想将值作为字典列表(即[{name1:rating1},{name2:rating2}]
)转回。
在python端,您可以执行以下操作:
from flask import Flask, request, render_template, jsonify
app = Flask(__name__)
@app.route('/run_query')
def api_sleuth():
query = request.args.get('query', '', type=str)
ret = None if parid == '' else jsonify(search(query))
return ret
@app.route('/')
@app.route('/index', methods=['GET'])
def index():
return render_template('index.html')
并且在html上(尽管您希望head和body元素位于单独的模板中:]]
<!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>
当然,您可以将json的格式设置与将其转储到
pre
元素时不同,但这是在我看来简单地显示它的好方法。