将代码作为脚本运行时,对外部 API 的调用有效,但在使用 FastAPI 运行相同代码时收到“500 内部服务器错误”响应?

问题描述 投票:0回答:1

我有一个应用程序可以预测图像中鱼的大小。我构建了一个 FastAPI 端点——

/predict/
——运行多步骤过程来做出预测。这些步骤包括对外部 API 的两次调用(不受我的控制,因此我只能看到它们返回的内容)。

当我仅从脚本运行代码时,例如通过 IDE(我使用 PyCharm),预测步骤的代码会正确运行,并且我会从两个 API 获得适当的响应。

第一个是Roboflow,这是运行脚本的输出示例(同样,我只是从命令行调用它或在 Pycharm 中点击“运行”):

2024-03-30 10:59:36,073 - DEBUG - Starting new HTTPS connection (1): detect.roboflow.com:443
2024-03-30 10:59:36,339 - DEBUG - https://detect.roboflow.com:443 "POST /fish_measure/1?api_key=AY3KX4KMynZroEOyXUEb&disable_active_learning=False HTTP/1.1" 200 914

第二个是Fishial,这是运行脚本(脚本或通过 PyCharm)的输出示例,其中必须获取令牌、url 等:

2024-03-30 11:02:31,866 - DEBUG - Starting new HTTPS connection (1): api-users.fishial.ai:443
2024-03-30 11:02:33,273 - DEBUG - https://api-users.fishial.ai:443 "POST /v1/auth/token HTTP/1.1" 200 174
2024-03-30 11:02:33,273 - INFO - Access token: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTE4MTE1NTMsImtpZCI6ImIzZjNiYWZlMTg2NGNjYmM3ZmFkNmE5YSJ9.YtlaecKMyxjipBDS97xNV3hYKcF3jRpOxTAVnwrxOcE
2024-03-30 11:02:33,273 - INFO - Obtaining upload url...
2024-03-30 11:02:33,582 - DEBUG - Starting new HTTPS connection (1): api.fishial.ai:443
2024-03-30 11:02:33,828 - DEBUG - https://api.fishial.ai:443 "POST /v1/recognition/upload HTTP/1.1" 200 1120
2024-03-30 11:02:33,829 - INFO - Uploading picture to the cloud...
2024-03-30 11:02:33,852 - DEBUG - Starting new HTTPS connection (1): storage.googleapis.com:443
2024-03-30 11:02:34,179 - DEBUG - https://storage.googleapis.com:443 "PUT /backend-fishes-storage-prod/6r9p24qp4llhat8mliso8xacdxm5?GoogleAccessId=services-storage-client%40ecstatic-baton-230905.iam.gserviceaccount.com&Expires=1711811253&Signature=gCGPID7bLuw%2FzUfv%2FLrTRPeQA060CaXQEqITPvW%2FWZ5GHXYKDRNCxVrUJ7UmpHVa0m60gIMFwFSQhYqsDmP3SkjI7ZnJSIEj53zxtOpcL7o2VGv6ZUuoowWwzmzqeM9yfbCHGI3TmtuW0lMhqAyi6Pc0wYhj73P12QU28wF8sdQMblHQLQVd1kFXtPl5yjSW12ADt4WEvB7dbnl7HmUTcL8WFS2SnJ1zcLljIbXTlRWcqc88MIcklSLG69z%2FJcUSh%2BeNxRp%2Fzotv5GitJBq9pF%2BzRt25lCt%2BYHGViJ46uu4rQapZBfACxsE762a1ZcrvTasy97idKRaijLJKAtZBRQ%3D%3D HTTP/1.1" 200 0
2024-03-30 11:02:34,180 - INFO - Requesting fish recognition...
2024-03-30 11:02:34,182 - DEBUG - Starting new HTTPS connection (1): api.fishial.ai:443
2024-03-30 11:02:39,316 - DEBUG - https://api.fishial.ai:443 "GET /v1/recognition/image?q=eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBMksyUEE9PSIsImV4cCI6bnVsbCwicHVyIjoiYmxvYl9pZCJ9fQ==--d37fdc2d5c6d8943a59dbd11326bc8a651f9bd69 HTTP/1.1" 200 10195

这是端点的代码:

from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Union

class PredictionResult(BaseModel):
    prediction: Union[float, str]
    eyeball_estimate: Union[float, str]
    species: str
    elapsed_time: float


@app.post("/predict/", response_model=PredictionResult)
    async def predict_fish_length(file: UploadFile = File(...)):
        try:
            # capture the start of the process so we can track duration
            start_time = time.time()
            # Create a temporary file
            temp_file = tempfile.NamedTemporaryFile(delete=False)
            temp_file_path = temp_file.name
    
            with open(temp_file_path, "wb") as buffer:
                shutil.copyfileobj(file.file, buffer)
    
            temp_file.close()
    
            prediction = process_one_image(temp_file_path)
            
            end_time = time.time()  # Record the end time
            elapsed_time = end_time - start_time  # Calculate the elapsed time
    
            return PredictionResult(
                prediction=prediction["prediction"][0],
                eyeball_estimate=prediction["eye_ratio_len_est"][0],
                species=prediction["species"][0],
                elapsed_time=elapsed_time
            )
    
        except Exception as e:
            # Clean up the temp file in case of an error
            os.unlink(temp_file_path)
            raise HTTPException(status_code=500, detail=str(e)) from e

我通过

uvicorn
运行此命令,然后尝试通过
curl
调用端点,如下所示:

curl -X POST http://127.0.0.1:8000/predict/ -F "file=@/Users/ianp.cook/repos/fishMeasuringTool/fish_measure/data/raw/18.1/18.1.JPG"

Roboflow API 调用工作正常,但现在我得到以下响应:

2024-03-30 10:48:09,166 - DEBUG - Starting new HTTPS connection (1): api.fishial.ai:443
2024-03-30 10:48:10,558 - DEBUG - https://api.fishial.ai:443 "GET /v1/recognition/image?q=eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBMWkyUEE9PSIsImV4cCI6bnVsbCwicHVyIjoiYmxvYl9pZCJ9fQ==--36e68766cd891eb0e57610e8fb84b76e205b639e HTTP/1.1" 500 89
INFO:     127.0.0.1:49829 - "POST /predict/ HTTP/1.1" 500 Internal Server Error

我不确定在哪里查看,或者打印/记录什么,以获得更多信息。我什至不确定错误是在我这边还是来自我正在调用的 API(尽管最后 GET 行的

500 89
让我认为它来自我正在调用的 API)。

非常感谢!

python fastapi http-status-code-500
1个回答
0
投票

您从 Fishial API 收到的错误消息指示 500 内部服务器错误。这表明服务器端(Fishial API)可能存在问题,而不是您的代码中。

查看 Fishial API 文档以确保您使用正确的端点和参数。

验证您在请求中传递了正确的 API 密钥(如果需要)。

© www.soinside.com 2019 - 2024. All rights reserved.