【问题标题】:Displaying flask json data in pythonanywhere在 pythonanywhere 中显示烧瓶 json 数据
【发布时间】:2016-11-15 08:06:50
【问题描述】:

我有一个简单的烧瓶应用程序正在运行,它会在用户输入后发布一些数据。目前,它在 json.dump 字典中显示这些数据,但我试图让它显示如下:

Name:     yyy
Shack:    yyy
Status:   yyy
Payments: vvv

我看到了一些与 jsonify 和其他 json 方法有关的问题,但我似乎无法让它们工作。 代码:

from flask import Flask, request, Response, render_template
import json
import sys
import numpy as np

app = Flask(__name__)

app.config['DEBUG'] = True

path = '/home/username/ishack/'
if path not in sys.path:
    sys.path.append(path)

client_db = np.genfromtxt('/home/username/ishack/client_db.csv', delimiter=',', dtype=None, names=True)



@app.route('/')
def form():
    return render_template('form_page.html')


@app.route('/address', methods=['POST'])
def display_info():
    address = request.form['address']
    ind = np.where(client_db['Shack'] == address)[0]
    res = {'Name': client_db[ind]['Name'][0],
            'Shack': client_db[ind]['Shack'][0],
            'Status': client_db[ind]['Status'][0],
            'Payments': client_db[ind]['Payments'][0]}
    return Response(json.dumps(res), mimetype='application/json')


if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

【问题讨论】:

    标签: python json flask pythonanywhere


    【解决方案1】:

    更改响应以呈现具有所需格式的页面。您无法对纯 JSON 响应进行样式化。

    @app.route('/address', methods=['POST'])
    def display_info():
        address = request.form['address']
        ind = np.where(client_db['Shack'] == address)[0]
        res = {'Name': client_db[ind]['Name'][0],
                'Shack': client_db[ind]['Shack'][0],
                'Status': client_db[ind]['Status'][0],
                'Payments': client_db[ind]['Payments'][0]}
        return render_template("address_page.html", address=res)
    

    address_page.html

    <table>
    {% for key,value in address.items() %}
        <tr>
            <td>{{key}}:</td><td>{{value}}</td>
        </tr>
    {% endfor %}
    </table>
    

    【讨论】:

    • 不错的一个!有没有办法按照问题中的描述对表格进行排序? (“姓名:”在顶部)
    • @wazzahenry 是的。您可以传递字典的有序列表,而不是传递字典。您应该查看 Jinja 模板文档以探索各种此类选项 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2019-08-19
    • 1970-01-01
    • 2020-07-15
    • 2020-11-04
    • 2021-05-23
    相关资源
    最近更新 更多