500未记录错误:在FastAPI中返回响应时出现内部服务器错误 [英] 500 Undocumented Error: Internal Server Error when returning response in fastapi
本文介绍了500未记录错误:在FastAPI中返回响应时出现内部服务器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用FAST API进行ML模型的预测。当我给出一个任务id并输入时,它应该把它添加到后台任务中,并相应地返回响应,但当我尝试这样做时,得到的结果是Error 500
。
添加task_id_globally
后,它在正常工作之前就开始抛出错误。
Error
File ".appmain.py", line 36, in post
return {'result': response_name[task_id_global]}
TypeError: list indices must be integers or slices, not NoneType
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
设置为None
,因此,当调用/predict_solubility
终结点时,它试图使用response_name[None]
从列表中检索元素;因此,出现错误。因此,您应该将task_id_global
设置为0
,它应该指向response_name
列表中的某个缺省值--即使还没有调用/predict
终结点--或者在第二个终结点内部执行检查,以确定task_id_global
是否不是None
,然后决定是否继续从列表中检索项。接下来,在/predict
内部终结点在使用task_id_global
之前将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。
这篇关于500未记录错误:在FastAPI中返回响应时出现内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文