簡體   English   中英

從 openapi 上傳的文件 swagger 未在后端收到 python function

[英]file uploaded from openapi swagger not getting received at backend python function

我正在嘗試使用 Openapi 3.0 和 swagger UI 從用戶那里獲取文件。 但是我沒有在我的 python function 中獲取該文件進行處理。下面是我的代碼:

代碼.py

def get_file():
    try:
        file=request.files.getlist('file')[0]
        with open(file, 'r') as fp:
            files = {"file": (file, fp)}
            response = requests.post(server, files=files)
            return response.json()
    except Exception as exc:
        return exc

api.yaml

  /get-result:
    post:
      summary: "A function to get file"
      operationId: "code.get_file"
      requestBody:
      content:
        application/json:
          schema:
            type: string
              format: binary
      responses:
        200:
          description: "executed successfully"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/myschema"
        500:
          description: Server is down.

我已經提到了這個鏈接: 在 Swagger 上傳文件並在 Flask 后端接收但是這是針對 Openapi 2.0 的,沒有幫助,因為我使用的是 openapi 3.0

檢查是否

request.files['file']

可以從請求中獲取文件,我不確定該行是否

file=request.files.getlist('file')[0]

實際上會得到正確的文件(或只是一個列表?)

下面的代碼更改幫助我解決了這個問題:

api.yaml

/get-result:
    post:
      summary: "A function to get file"
      operationId: "code.get_file"
      requestBody:
        content:
          multipart/form-data:
            schema:
              type: object
              properties:
                file:
                  type: string
                  format: binary
      responses:
        200:
          description: "executed successfully"
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/myschema"
        500:
          description: Server is down.

在下面的 code.py 中,必須將參數“文件”傳遞給 function,這也是 openapi 規范中的字段名稱。 使用 post 請求發送文件指針和文件名也很重要

代碼.py

def get_file(file):
    try:
        fp=file.read()
        file.save(file.filename)
        response = requests.post(server, files={"file":(file.filename,fp)})
        return response.json()
    except Exception as exc:
        return exc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM