首页 > 解决方案 > 有没有办法使用烧瓶读取表单数据和上传的文件(多部分/表单数据)

问题描述

我公开了一个带有 content-type=multipart/form-data 的烧瓶 api,它将 json 和 .zip 文件作为输入。当我尝试阅读时,我可以获得 zip 文件。但是,我无法读取 json 文件。我尝试了几件事,但没有一个有 json 数据。这甚至支持吗?

我正在使用flask restplus解析器使用“werkzeug.datastructures import FileStorage”读取文件内容,而为了获取json,我使用了下面给出的不同选项,没有工作->request.form

->dict(request.form)

->request.files.get_json(force=True)

->api.payload

from werkzeug.datastructures import FileStorage, ImmutableMultiDict


parser= api.parser()
parser.add_argument('opc-retry-token', location='headers',required='true')

parser.add_argument('file', location='files', type=FileStorage, required=True)

def init(self):
        args = parser.parse_args()
        token = args['opc-retry-token']
        self.token=token
        self.args=args
        logger.info(args) 

# above log  gives {'opc-retry-token': '1234', 'file': <FileStorage:         


@ns.route('/prepare')
@api.expect(parser)
class OICPrepare(Resource):

    @api.expect(oic_prepare)
    def post(self):

        init(self)
        logger.info(request.form)
# above log gives 'None'
        data = dict(request.form)
        logger.info(data)
# above log gives ImmutableMultiDict([])

        logger.info(request.files.get_json(force=True))
#above log gives {}       
        upload_file = self.args['file']
        upload_file.save('/oic_admin/wallet.zip')
#above save command does the zip file properly 

我期待 zip 文件和 json 都能被烧瓶 api 读取。

标签: resthttpflask

解决方案


推荐阅读