簡體   English   中英

如何解析 webargs 中的多部分表單數據?

[英]How to parse a multipart form-data in webargs?

我需要使用webargs解析帶有附件的多部分表單數據。 此刻我有下一個model:

RAW_ARGS = {
    'file': fields.Field(
        required=True,
        validate=lambda file: file.mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        location='files'),
    'currency': fields.Int(required=True, validate=validate.OneOf([
        ECurrency.EUR.value,
        ECurrency.RUB.value,
        ECurrency.USD.value
    ]), location='form')
}

class RawResource(Resource):

    @token_required
    @use_args(RAW_ARGS)
    def post(self, args):
        return '', 204

但是根據請求,我得到The request was well-formed but was unable to be followed due to semantic errors. 422 HTTP 狀態代碼錯誤。

以下是來自 Chrome 網絡的請求副本:

Request URL: http://localhost:5000/api/v1/raw
Request Method: POST
Status Code: 422 UNPROCESSABLE ENTITY
Remote Address: 127.0.0.1:5000
Referrer Policy: no-referrer-when-downgrade
Access-Control-Allow-Origin: http://localhost:4200
Content-Length: 186
Content-Type: application/json
Date: Tue, 28 Apr 2020 12:41:08 GMT
Server: Werkzeug/1.0.1 Python/3.8.1
Vary: Origin
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Authorization: Bearer <token>
Connection: keep-alive
Content-Length: 405453
Content-Type: multipart/form-data
Host: localhost:5000
Origin: http://localhost:4200
Referer: http://localhost:4200/upload
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.122 Safari/537.36
------WebKitFormBoundary5KsexIuuVJnu3TnU
Content-Disposition: form-data; name="currency"

840
------WebKitFormBoundary5KsexIuuVJnu3TnU
Content-Disposition: form-data; name="file"; filename="test.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet


------WebKitFormBoundary5KsexIuuVJnu3TnU--

解析多部分表單數據的正確方法是什么?

PS我的服務器是Flask應用程序。

寫兩次@use_args,通過兩次。 我已經相應地編輯了您的代碼

RAW_ARGS = {
    'file': fields.Field(
        required=True,
        validate=lambda file: file.mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        location='files'),
    'currency': fields.Int(required=True, validate=validate.OneOf([
        ECurrency.EUR.value,
        ECurrency.RUB.value,
        ECurrency.USD.value
    ]), location='form')
}
class RawResource(Resource):
    @token_required
    @use_args(RAW_ARGS['file'])
    @use_args(RAW_ARGS['currency'])
    def post(self, args_file, args_currency):
        return '', 204

暫無
暫無

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

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