如何在树莓派的Flask服务器中将Python JSON转为HTML表格?
Got it, so you want to turn that JSON response from your /detect endpoint into a nice HTML table? Let's break this down into two straightforward approaches—one quick inline method, and a cleaner template-based approach that's better for long-term maintainability.
Approach 1: Inline HTML Generation (Quick & Simple)
This method builds the HTML table directly in your detect() function, no extra files needed. We'll parse the JSON output from detect.py into a Python dictionary, then construct the HTML string row by row.
First, update your Flask code with these changes:
from flask import Flask import os import json app = Flask(__name__) @app.route('/') def index(): return 'Hello world' @app.route('/detect') def detect(): # Read and clean the output from detect.py labels_str = os.popen('python3 detect.py').read().strip() # Parse the string into a Python dictionary (add error handling!) try: labels = json.loads(labels_str) except json.JSONDecodeError: return "Oops, failed to parse detection results. Check detect.py's output!", 500 # Build the HTML table with basic styling html_content = """ <!DOCTYPE html> <html> <head> <title>Detection Results</title> <style> table { border-collapse: collapse; width: 60%; margin: 30px auto; } th, td { border: 1px solid #ccc; padding: 10px; text-align: left; } th { background-color: #f8f9fa; font-weight: bold; } h2 { text-align: center; color: #333; } </style> </head> <body> <h2>Detection Status</h2> <table> <tr> <th>Name</th> <th>Detected?</th> </tr> """ # Loop through the dictionary to add table rows for name, status in labels.items(): html_content += f"<tr><td>{name}</td><td>{status}</td></tr>" # Close the HTML structure html_content += """ </table> </body> </html> """ return html_content if __name__ == '__main__': app.run(debug=True, port=8000, host='0.0.0.0')
Approach 2: Template-Based Rendering (Cleaner & Scalable)
If you plan to expand the page later (add more UI elements, styling), using Flask's built-in Jinja2 templating is the way to go. This separates your HTML from your Python code.
Step 1: Create a Templates Folder
First, make a templates folder in your Flask app directory (this is where Flask looks for template files by default):
your-app/ ├── app.py ├── detect.py └── templates/ └── results.html
Step 2: Add the HTML Template (templates/results.html)
<!DOCTYPE html> <html> <head> <title>Detection Results</title> <style> table { border-collapse: collapse; width: 60%; margin: 30px auto; } th, td { border: 1px solid #ccc; padding: 10px; text-align: left; } th { background-color: #f8f9fa; font-weight: bold; } h2 { text-align: center; color: #333; } </style> </head> <body> <h2>Detection Status</h2> <table> <tr> <th>Name</th> <th>Detected?</th> </tr> {% for name, status in labels.items() %} <tr> <td>{{ name }}</td> <td>{{ status }}</td> </tr> {% endfor %} </table> </body> </html>
Step 3: Update Your Flask Code
Modify the detect() function to use render_template instead of building HTML inline:
from flask import Flask, render_template import os import json app = Flask(__name__) @app.route('/') def index(): return 'Hello world' @app.route('/detect') def detect(): labels_str = os.popen('python3 detect.py').read().strip() try: labels = json.loads(labels_str) except json.JSONDecodeError: return "Oops, failed to parse detection results. Check detect.py's output!", 500 # Pass the dictionary to the template return render_template('results.html', labels=labels) if __name__ == '__main__': app.run(debug=True, port=8000, host='0.0.0.0')
Key Notes to Remember
- Validate JSON Output: Make sure
detect.pyoutputs a valid JSON string (like{"John":"Yes","David":"No"}with no extra newlines or typos). Thestrip()method helps remove any leading/trailing whitespace that might break parsing. - Error Handling: The
try/exceptblock catches cases where the JSON parsing fails—this prevents your app from crashing ifdetect.pyreturns unexpected output. - Styling: The CSS in the examples is basic, but you can tweak it to match your desired look (change colors, width, padding, etc.).
内容的提问来源于stack exchange,提问作者user2308127

