Search code examples
pythonjsonflaskpythonanywhere

Displaying flask json data in pythonanywhere


I have a simple flask app running, that posts some data after a user input. At the moment, it displays this data in a json.dump dictionary, but I am trying to get it to display as follows:

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

I've seen some questions relating to jsonify and other json methods, but I can't seem to get them to work. Code:

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)

Solution

  • Change the response to render a page with the desired formatting. You cannot stylize a plain JSON response.

    @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>