【问题标题】:Uploading images in FastAPI post request causes 400 Bad Request在 FastAPI 发布请求中上传图像会导致 400 Bad Request
【发布时间】:2020-06-17 12:40:32
【问题描述】:

我想通过发布请求获取图像然后阅读它。我正在尝试这样做:

import numpy as np
from PIL import Image
from fastapi import FastAPI, File, UploadFile, HTTPException, Depends
app = FastAPI()
@app.post("/predict_image")
    @logger.catch
    def predict_image(predict_image: UploadFile = File(...)):
        logger.info('predict_image POST request performed')
        try:
            pil_image = np.array(Image.open(predict_image.file))
        except:
            raise HTTPException(
                status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail="Unable to process file"
            )
        pred = pil_image.shape
        logger.info('predict_image POST request performed, shape {}'.format(pred))
    return {'input_shape': pred}

调用post请求返回INFO: 127.0.0.1:59364 - "POST /predict_image HTTP/1.1" 400 Bad Request

如何解决?

更新:

来自官方教程的示例返回相同的异常:

@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

【问题讨论】:

    标签: image post file-upload fastapi


    【解决方案1】:

    你可能需要安装python-multipart

    只是:

    pip install python-multipart
    

    【讨论】:

      【解决方案2】:

      以这种方式修复:

      @app.post("/predict_image/")
      @logger.catch
      def make_inference(file: bytes = File(...)):
          try:
              pil_image = np.array(Image.open(BytesIO(file)))
      
          except:
              raise HTTPException(
                  status_code=HTTP_422_UNPROCESSABLE_ENTITY, detail="Unable to process file"
              )
      

      【讨论】:

        猜你喜欢
        • 2012-01-12
        • 1970-01-01
        • 2016-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-04
        • 1970-01-01
        • 2012-08-31
        相关资源
        最近更新 更多