json KeyError:FastAPI应用程序中的“response_data”

yrwegjxp  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(154)

我正在构建一个fastAPI应用程序,它接收消息和图像,并根据图像提供的消息给予编辑后的图像。问题是应用程序返回错误。

Traceback (most recent call last):
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\starlette\middleware\errors.py", line 162, in __call__
    await self.app(scope, receive, _send)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\starlette\middleware\exceptions.py", line 79, in __call__
    raise exc
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\starlette\middleware\exceptions.py", line 68, in __call__
    await self.app(scope, receive, sender)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 21, in __call__
    raise e
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\fastapi\middleware\asyncexitstack.py", line 18, in __call__
    await self.app(scope, receive, send)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\starlette\routing.py", line 718, in __call__
    await route.handle(scope, receive, send)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\starlette\routing.py", line 276, in handle
    await self.app(scope, receive, send)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\starlette\routing.py", line 66, in app
    response = await func(request)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\fastapi\routing.py", line 237, in app
    raw_response = await run_endpoint_function(
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\venv\lib\site-packages\fastapi\routing.py", line 163, in run_endpoint_function
    return await dependant.call(**values)
  File "C:\Users\abu aisha\Documents\whatsappPhotoEditor\main.py", line 63, in reply
    image_url = image_response.json()["response_data"]["result"]["output"][0]
KeyError: 'response_data'

下面是fastAPI应用程序的代码,我已经做了一些研究,但不能拿出任何实际的东西,这就是为什么我寻求社区的帮助

from fastapi import FastAPI, Form, File, UploadFile
import requests
from utils import send_message
from dotenv import load_dotenv
import os
import json

load_dotenv()

app = FastAPI(debug=True)

api_key = os.getenv("MONSTER_API_KEY")
bearer_token = os.getenv("BEARER_TOKEN")
whatsapp_number = os.getenv("TO_NUMBER")

@app.post("/message")
async def reply(file: UploadFile = File(...), prompt: str = Form(...)):
    file.filename = "image.jpg"
    contents = await file.read()

    with open(f"{file.filename}", "wb") as f:
        f.write(contents)

    url = "https://api.monsterapi.ai/apis/add-task"

    payload = {
        "model": "pix2pix",
        "data": {
            "prompt": prompt,
            "negprompt": "",
            "steps": 50,
            "guidance_scale": 12.5,
            "init_image_url": file.filename,
            "image_guidance_scale": 1.5
        }
    }
    headers = {
        'x-api-key': api_key,
        'Authorization': bearer_token,
        'Content-Type': 'application/json'
    }

    response = requests.post(url, headers=headers, json=payload)
    response.raise_for_status()
    process_id = response.json()["process_id"]

    response_url = "https://api.monsterapi.ai/apis/task-status"
    response_payload = {
        "process_id": process_id
    }
    response_headers = {
        'x-api-key': api_key,
        'Authorization': bearer_token,
        'Content-Type': 'application/json'
    }

    image_response = requests.request("POST", response_url, headers=response_headers, data=response_payload)

    image_url = image_response.json()["response_data"]["result"]["output"][0]

    send_message(whatsapp_number, image_url)

    return ""

这是respons.json()的内容

{'message': 'Request accepted successfully', 'process_id': 'eee2c49e-083a-11ee-b335-99c647f2e5d3'}

这是image_response.json()的内容

{'message': 'Request processed successfully', 'response_data': {'process_id': 'eee2c49e-083a-11ee-b335-99c647f2e5d3', 'status': 'COMPLETED', 'result': {'output': ['https://processed-model-result.s3.us-east-2.amazonaws.com/eee2c49e-083a-11ee-b335-99c647f2e5d3_0.png']}, 'credit_used': 4, 'overage': 0}}

这是send_message()函数

import logging
from dotenv import load_dotenv
import os
from twilio.rest import Client

load_dotenv()

account_sid = os.getenv("TWILIO_ACCOUNT_SID")
auth_token = os.getenv("TWILIO_AUTH_TOKEN")
client = Client(account_sid, auth_token)
twilio_number = os.getenv('TWILIO_NUMBER')

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Sending message logic through Twilio Messaging API
def send_message(to_number, media):
    try:
        message = client.messages.create(
            from_=f"whatsapp:{twilio_number}",
            to=f"whatsapp:{to_number}",
            media_url=[media]
            )
        logger.info(f"Message sent to {to_number}: {message.media_url}")
    except Exception as e:
        logger.error(f"Error sending message to {to_number}: {e}")
to94eoyn

to94eoyn1#

KeyError由于字典键查找错误而引发。换句话说,当您尝试访问不在dict中的密钥时。
测试您在问题中提供的image_response字典,它应该像预期的那样工作,而不会得到任何KeyError。因此,请确保每次您收到JSON响应并尝试访问它时response_data都在dict中。下面的示例使用了dict和您提供的用于从response_data中提取image_url的代码,并演示了该代码应按预期工作。

示例

image_response = {
    "message": "Request processed successfully",
    "response_data": {
        "process_id": "eee2c49e-083a-11ee-b335-99c647f2e5d3",
        "status": "COMPLETED",
        "result": {
            "output": [
                "https://processed-model-result.s3.us-east-2.amazonaws.com/eee2c49e-083a-11ee-b335-99c647f2e5d3_0.png"
            ]
        },
        "credit_used": 4,
        "overage": 0,
    },
}

image_url = image_response["response_data"]["result"]["output"][0]
print(image_url)

重要

您应该避免在async def端点中使用requests模块。请查看this answer以找出为什么不这样做,以及this answerthis answer如何在FastAPI应用程序中正确地发出HTTP请求。

相关问题