我正在使用 FastAPI 通过 ML 模型进行预测。当我给一个task_id
and input
,应用程序应将其添加到后台任务并相应地返回响应。然而,我得到Error 500
当我尝试这样做时。
添加后task_id_globally
,它在正常工作之前就开始抛出错误。
Error
File ".\app\main.py", line 36, in post
return {'result': response_name[task_id_global]}
TypeError: list indices must be integers or slices, not NoneType
Code
task_id_global = None
@app.get('/predict')
async def predict(task_id:int, background_tasks: BackgroundTasks,solute,solvent):
task_id_global = task_id
if task_id == 0:
background_tasks.add_task(predictions,solute,solvent)
return {'success'}
elif task_id == 1:
background_tasks.add_task(predictions_two,solute)
return {'success'}
else:
return "Give proper task_id"
response_name = [response, attach_drug_name()]
@app.get('/predict_solubility')
async def post():
return {'result': response_name[task_id_global]}
您已设置task_id_global
to None
,因此,当调用时/predict_solubility
端点,它正在尝试使用从列表中检索元素response_name[None]
;因此,出现错误。所以你应该设置task_id_global
to 0
,它应该指向你的一些默认值response_name
列表 - 即使/predict
端点尚未被调用 - 或在第二个端点内执行检查以查看是否task_id_global
is not None
然后决定是否继续从列表中检索项目。接下来,里面/predict
端点声明task_id_global
在使用它之前作为全局(使用global
关键字),因为按照当前声明的方式,它被解释为局部变量,因此全局变量永远不会受到发生的任何更改的影响task_id_global
在端点内(看看here).
task_id_global = None
@app.get('/predict')
async def predict(task_id:int,solute,solvent):
global task_id_global
task_id_global = task_id
...
此外,根据您的任务(例如,如果您有多个请求同时访问该全局变量),您可能需要考虑其他选项,例如 Redis。看一下这个答案.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)