我正在使用快速 API 來預測機器學習模型。當我給出 task_id 并輸入時,它應該將其添加到后臺任務并相應地回傳回應,但是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
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]}
uj5u.com熱心網友回復:
您已設定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內部發生的任何更改的影響端點(看看在這里)。
async def predict(task_id:int,solute,solvent):
global task_id_global
task_id_global = task_id
...
此外,根據您的任務(例如,如果您有多個請求同時訪問該全域變數),您可能需要考慮其他選項,例如 Redis。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439652.html
