【问题标题】:Python restplus API to upload and dowload filesPython restplus API 上传和下载文件
【发布时间】:2017-03-25 15:58:45
【问题描述】:

使用 python flask_restplus 发布和获取获取和推送文件的正确方法是什么? xlsx 到服务器?

marshaling 是否需要用于此?

参考:https://philsturgeon.uk/api/2016/01/04/http-rest-api-file-uploads/

此答案提供一般信息,但不在 python>flask>restplus 上下文中:REST API File Upload

【问题讨论】:

  • 如果在单个 post 方法上获得多个类型/事件,我认为这种模块样式无法成功。发送方法(文件上传)是post,但我从未使用过这种方法,因为需要检查文件内容以便在某处写入!在大文件上很复杂,需要与目标同步源(不删除或移动只制作差异。)。有时需要对源代码/html 输出使用额外的修订,以免丢失任何数据或 escape_multiple_io 操作。如果文件较小,请使用 Base64 编码的 bz2 内容。大文件(很大?(在您的服务器上))在创建/修改过程中存在很大风险。

标签: python rest upload flask-restplus


【解决方案1】:

首先你需要配置一个解析器

# parsers.py
import werkzeug
from flask_restplus import reqparse

file_upload = reqparse.RequestParser()
file_upload.add_argument('xls_file',  
                         type=werkzeug.datastructures.FileStorage, 
                         location='files', 
                         required=True, 
                         help='XLS file')

然后将新资源添加到您的 api 命名空间

# api.py
import …
import parsers

@api.route('/upload/')
class my_file_upload(Resource):
    @api.expect(parsers.file_upload)
    def post(self):
        args = parsers.file_upload.parse_args()
        if args['xls_file'].mimetype == 'application/xls':
            destination = os.path.join(current_app.config.get('DATA_FOLDER'), 'medias/')
            if not os.path.exists(destination):
                os.makedirs(destination)
            xls_file = '%s%s' % (destination, 'custom_file_name.xls')
            args['xls_file'].save(xls_file)
        else:
            abort(404)
        return {'status': 'Done'}

我希望这会有所帮助。

【讨论】:

  • 要以一种宁静的方式进行,我认为您应该首先创建一个文件对象:POST /api/v1/file {"meta": "some data"},然后您收到文件对象:{"meta": "some data", "created_time": "timestamp", "id": 1},然后使用 PUT 和二进制文件添加附件文件如下:PUT /api/v1/file/1/attachment
  • PUT 或 POST(如果您使用简单的 html 表单)
  • @samurai 我同意这通常是要走的路。但是,这种方法的问题在于 Flask-RESTPlus 不支持直接将二进制 blob 作为请求主体传递(Swagger 2.0 也不支持)。相反,人们不得不求助于 k3z 在他的回答中建议的表单数据方法——至少如果人们希望使用 Swagger 描述文件上传 API(特别是对于请求的预期 Content-Type)。
猜你喜欢
  • 2020-08-25
  • 1970-01-01
  • 2021-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 2013-05-11
  • 2021-09-30
相关资源
最近更新 更多