使用Python Flask从Swagger UI下载文件

时间:2018-06-26 10:46:17

标签: python flask swagger swagger-ui

我正在尝试使用Python Flask API从Swagger UI下载文件。我在服务器上名为“ server_data”的目录中存储了一些XML文件,并且在将“ file_id”传递给API后,我试图使用GET请求返回文件的下载链接。我已经拖网了,但是找不到解决我问题的方法。 目前,该代码将返回在Swagger UI的响应正文中打印出的xml文本的blob,因此我至少知道该文件的目录是正确的。 这是我的Python代码:

def fetch_file(file_id):

    try:
        if len(glob.glob("server_data/" + str(file_id) + ".*")) != 0:
            root_dir = os.path.dirname(os.getcwd())
            pathToFile = glob.glob("server_data/" + str(file_id) + ".*")[0]
            filename = pathToFile.replace("server_data/", "")

            return flask.send_from_directory(directory = os.path.join(root_dir, "python-flask-server", "server_data"), filename = filename)

        else:

            return Response('{"error" : "No such file."}', status=200, mimetype='application/json')

    except Exception as e:
        print(str(e))
        return Response('{"error" : "Failed, '+str(e)+'"}', status=400, mimetype='application/json')

这是YAML文件中与此请求相关的代码:

/files/{file_id}:
get:
  tags:
  - "Download File"
  summary: "Download data set that is on the server."
  description: "With a known ID of a file on the server, this will download the data set of the event corresponding to that ID."
  operationId: "fetch_file"
  produces:
    - "application/xml"
  parameters:
  - name: "file_id"
    in: "path"
    description: "ID of the file to fetch."
    required: true
    type: "string"
  responses:
    200:
      description: "Request was handled successfully and results were returned."
      schema:
        type: "file"

我对Flask和Swagger还是很陌生,所以我们将不胜感激。

0 个答案:

没有答案