0

I have installed flask in raspberry pi.

from flask import Flask
from flask import jsonify
import os
import cv2
import numpy as np
app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello world'

@app.route('/detect')
def detect():
    labels = os.popen('python3 detect.py').read()
    return jsonify(labels)

if __name__ == '__main__':
    app.run(debug=True, port=8000, host='0.0.0.0')

in the detect() method i have converted the labels into JSON. It is of the format {"John":"Yes","David":"No"} format. But I need to convert this JSON into a HTML table and render it as a html template. so that it looks like

Name  Status
John  Yes
David No

How do I achieve it?? I have seen lot of questions in StackOverflow but I don't get any correct solution for my question.

4
  • You should use html template. flask.pocoo.org/docs/0.12/templating Commented Mar 20, 2018 at 17:03
  • {% for name, status in data.items %}<tr><td>{{ name }}</td><td>{{ status }}</td></tr>{% endfor %} where you supply this dictionary with the name data to your template. Commented Mar 20, 2018 at 17:05
  • use render_template to render a html passing in the labels as data: return render_template('template.html', labels=labels) not sure if you should jsonify if it comes in as a list then you should be fine using that in jinja2 temaplate -- Flask quickstart is really helpful recommend going through that Commented Mar 20, 2018 at 17:05
  • @sytech I have edited like this return render_template('template.html' , data = labels) but it doesn't show any html table Commented Mar 20, 2018 at 17:39

1 Answer 1

3

First import render_template_string from flask by adding from flask import render_template_string in the script

then in the route instead of return jsonify(labels) replace with the below,

return render_template_string('''


    <table>
            <tr>
                <td> Name </td> 
                <td> Status </td>
            </tr>


    {% for name, status in labels.items() %}

            <tr>
                <td>{{ name }}</td> 
                <td>{{ status }}</td>
            </tr>

    {% endfor %}


    </table>
''', labels=labels)

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.