Flask单HTML页面调用多路由函数渲染统计数据失效问题及代码修正请求
Fixing Your Flask Placeholder Replacement Issue
Let's break down why your placeholders aren't being replaced and fix the code step by step:
Key Issues in Your Original Code
- Incorrect Route Setup: Your routes use dynamic parameters (
<count_pending1>) that aren't necessary here, and there's no single route that serves the homepage with both values calculated and replaced. - Partial Replacement: Each route only replaces one placeholder, so even if you visited one of those routes, the other placeholder would remain untouched.
- Type Mismatch: In
count_pending2, you're trying to replace a string placeholder with an integer, which would throw an error (though you might not have seen it yet).
Corrected Python Code
import flask import pandas as pd app = flask.Flask("app_monitoringissues") # Helper function to safely read HTML files def get_html(page_name): with open(f"{page_name}.html", "r") as html_file: return html_file.read() # Helper functions to calculate each count (separating logic from routes) def calculate_pending_check(): df = pd.read_csv("sortdata.csv") count_pending = len(df[df["Status_Issue"].astype(str).str.contains("Pending-to be checked")]) count_na = df["Status_Issue"].isna().sum() return count_pending + count_na def calculate_pending_cp(): df = pd.read_csv("sortdata.csv") return len(df[df["Status_Issue"].astype(str).str.contains("Pending CP")]) # Single route for the homepage that replaces both placeholders @app.route("/") @app.route("/homepage") def homepage(): html_page = get_html("homepage") # Get both calculated values number1 = calculate_pending_check() number2 = calculate_pending_cp() # Replace both placeholders with string-converted values html_page = html_page.replace("$$NUMBER1$$", str(number1)) html_page = html_page.replace("$$NUMBER2$$", str(number2)) return html_page # Run the Flask app if __name__ == "__main__": app.run(debug=True)
What Changed?
- Single Homepage Route: We created a single route (
/and/homepage) that handles both calculations and replaces both placeholders in one go. This ensures when you visit the homepage, both numbers are populated. - Separated Logic: Moved the count calculations into helper functions to keep the route clean and reusable.
- Safe File Handling: Used a
withstatement to open HTML files (better practice for resource management). - Fixed Type Conversion: Converted all integer results to strings before replacing placeholders to avoid errors.
How to Test
- Save the corrected Python code.
- Make sure your
sortdata.csvis in the same directory. - Run the script—Flask will start a server at
http://localhost:5000. - Visit that URL (or
/homepage) and you'll see both placeholders replaced with their respective counts.
Your HTML code doesn't need any changes—it's already set up correctly with the placeholders.
内容的提问来源于stack exchange,提问作者mollieda
相关产品推荐
相关产品推荐

