代码之家  ›  专栏  ›  技术社区  ›  Dawny33

如何将json负载和图像一起发送到FastAPI实例?

  •  0
  • Dawny33  · 技术社区  · 4 年前

    我使用FastAPI接收图像,方法如下:

    import cv2
    import numpy as np
    from fastapi import FastAPI, File, UploadFile
    
    app = FastAPI()
    
    @app.post('/file')
    def _file_upload(my_file: UploadFile = File(...)):
        image_bytes = my_file.file.read()
        decoded = cv2.imdecode(np.frombuffer(image_bytes, np.uint8), -1)
        return {"file_size": my_file.filename}
    

    现在,如果我想把json负载和图像一起发送,我该怎么做?

    例子:

    import requests
    filename = "test_image.jpeg"
    files = {'my_file': (filename, open(filename, 'rb')), 'some_other_data': 'hello'}
    response = requests.post('http://127.0.0.1:8000/file', files=files)
    print(response.json())
    

    some_other_data ?

    0 回复  |  直到 4 年前
        1
  •  -1
  •   Yagiz Degirmenci    4 年前

    您正在发送一个如下所示的请求

    files = {
        'my_file': (filename, open(filename, 'rb')), 
        'some_other_data': 'hello'
    }
    

    端点需要两个参数 my_file some_other_data ,自从 一些其他数据 是一个 str

    from fastapi import FastAPI, File, UploadFile, Body
    
    @app.post('/file')
    def my_endpoint(my_file: UploadFile = File(...), some_other_data: str = Body(...)):
        ...
    
    推荐文章