Flask新手求助:如何将/predict路由的predictions变量渲染到/hello路由
Hey there! Let's work through how to get that predictions variable from your /predict POST route over to the /hello page. Since you're new to Flask, I'll walk you through two simple, practical approaches that fit most beginner use cases.
Approach 1: Use Flask Session (Recommended for Temporary, Sensitive Data)
Flask's built-in session lets you store small amounts of data securely in the user's browser (encrypted with a secret key). Perfect for passing temporary results like your predictions.
Step 1: Set a Secret Key
First, you need to add a secret key to your app—this is required for Flask to encrypt session data. Pick a random, secure string (you can generate one using secrets.token_hex(16) in Python).
from flask import Flask, request, session, redirect, url_for, render_template import pandas as pd import joblib app = Flask(__name__) app.secret_key = 'your-secure-random-secret-key-here' # Replace with your own unique key
Step 2: Store Predictions in Session & Redirect
Update your /predict route to calculate predictions, store them in the session, then redirect to /hello:
@app.route('/predict', methods=['POST']) def apicall(): test_json = request.get_json() test = pd.read_json(test_json, orient='records') query_df = pd.DataFrame(test) clf = 'kmeans__model.pkl' print("Loading the model...") with open(clf,'rb') as f: lin_reg_model = joblib.load(f) # Calculate your predictions (added this line since your code cut off) predictions = lin_reg_model.predict(query_df) # Store predictions in session (convert to list since numpy arrays aren't serializable) session['predictions'] = predictions.tolist() # Redirect to the /hello route return redirect(url_for('hello'))
Step 3: Retrieve Predictions in /hello Route
Now, update your /hello route to pull the predictions from the session and pass them to your template:
@app.route('/hello') def hello(): # Get predictions from session (default to empty list if not present) predictions = session.get('predictions', []) # Optional: Clear the session if you don't want predictions to persist after page load # session.pop('predictions', None) return render_template('hello.html', predictions=predictions)
Step 4: Display Predictions in Your Template
In your hello.html template, add code to render the predictions:
<h1>Your Predictions</h1> {% if predictions %} <ul> {% for pred in predictions %} <li>{{ pred }}</li> {% endfor %} </ul> {% else %} <p>No predictions found!</p> {% endif %}
Approach 2: Use Query Parameters (For Simple, Non-Sensitive Data)
If your predictions are short (like a single value or small list), you can pass them directly in the URL as query parameters. Note: This isn't secure for sensitive data, and URL length is limited.
Update /predict Route
@app.route('/predict', methods=['POST']) def apicall(): # ... (keep your existing code to load model and calculate predictions) predictions = lin_reg_model.predict(query_df) # Convert predictions to a comma-separated string predictions_str = ','.join(map(str, predictions.tolist())) # Redirect to /hello with predictions as a query parameter return redirect(url_for('hello', predictions=predictions_str))
Update /hello Route
@app.route('/hello') def hello(): # Get the query parameter value predictions_str = request.args.get('predictions', '') # Convert the string back to a list of floats predictions = list(map(float, predictions_str.split(','))) if predictions_str else [] return render_template('hello.html', predictions=predictions)
Key Notes
- Session Tips: Session data is encrypted, so it's safe for sensitive info. Don't store large datasets here—keep it small (like prediction results).
- Query Parameter Limits: Avoid using this for large prediction lists, as URLs have a maximum length (usually around 2000 characters).
- Serialization: Make sure any data you store in session or pass via URL is serializable (numpy arrays need to be converted to lists/strings first).
内容的提问来源于stack exchange,提问作者Rustem Kussaiynov

