500 Undocumented Error: Internal Server Error when returning response in FastAPI
500 Undocumented Error: Internal Server Error when returning response in FastAPI
我正在使用 FastAPI 通过 ML 模型进行预测。当我给出 task_id
和 input
时,应用程序应将其添加到后台任务并相应地 return 响应。但是,当我尝试这样做时,我得到了 Error 500
。
添加 task_id_globally
后,它在正常工作之前开始抛出错误。
错误
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
代码
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
为全局变量,然后再使用它(使用 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。看看 this answer.
我正在使用 FastAPI 通过 ML 模型进行预测。当我给出 task_id
和 input
时,应用程序应将其添加到后台任务并相应地 return 响应。但是,当我尝试这样做时,我得到了 Error 500
。
添加 task_id_globally
后,它在正常工作之前开始抛出错误。
错误
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
代码
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
为全局变量,然后再使用它(使用 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。看看 this answer.