Flask项目mypred变量引用前未赋值UnboundLocalError问题求助
问题根因
- 你的路由同时处理GET、POST两种请求,用户首次访问页面触发GET请求时,
if request.method == "POST"分支不会执行,mypred变量未定义就直接传给模板,就会触发NameError,这也是你删掉name=mypred后程序就正常的核心原因 - 多余的
global pred全局变量声明没有必要,反而会引发多请求场景下的变量污染问题 - 你把模型加载逻辑写在预测函数里,每次请求都会重新读取一次model.pkl文件,性能极低,频繁请求还可能触发文件IO异常
修复后的Python代码
!pip install flask-ngrok from flask import Flask, render_template, request from flask_ngrok import run_with_ngrok import pickle app = Flask(__name__, template_folder="templates") run_with_ngrok(app) # 全局仅加载一次模型,避免每次请求重复读文件 model = pickle.load(open('model.pkl', 'rb')) def cloud_prediction(time): return float(model.forecast(time)[0][time-1]) @app.route("/", methods= ["GET", "POST"]) def final(): # 给预测结果设置默认空值,适配GET请求场景 mypred = "" if request.method =="POST": time = int(request.form["time"]) mypred = cloud_prediction(time) print(mypred) return render_template("index.html", name= mypred) if __name__=="__main__": app.run()
可选HTML语法优化
你当前的HTML存在两处不影响核心功能的语法问题,可按需修复:
- 重复定义了
<body>标签,可删除第二个<body bgcolor='black' text='white'>,把属性合并到第一个body标签上 <h1>标签未闭合,末尾修改为</h1><font>标签未闭合,补充</font>闭合标签
修复后的参考HTML:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>WeatherNexus Inc.</title> <meta name="description" content="A fortune teller for cloud activity."> <meta name="author" content="Jesus_Lopez"> <meta property="og:title" content="WeatherNexus Inc."> <meta property="og:type" content="website"> <meta property="og:description" content="A fortune teller for cloud activity."> </head> <body bgcolor='black' text='white'> <h1>WeatherNexus Inc.</h1> <p> <font size=15 class="text-center"> Please input the time when you want to predict the cloud coverage. Timesteps are in 5 min increments. Ex: 6 = 30min </font> </p> <form action="/" method="POST"> <input type="number" name="time" placeholder="Input Time here"> <input type="submit"> <p>Here is your residual output: </p>{{name}} </form> </body> </html>
内容的提问来源于stack exchange,提问作者jesse lopez
相关产品推荐
相关产品推荐

