You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pytest测试Flask应用时出现422错误:必填字段数据缺失

问题解决:Flask-Smorest POST接口测试返回422必填字段缺失

核心原因

测试代码中使用client.post()的data参数传递数据,这会以application/x-www-form-urlencoded(表单)格式发送请求,但Flask-Smorest的@blp.arguments(StoreSchema)装饰器默认从JSON请求体(application/json)解析参数,因此接口无法识别表单格式的数据,导致始终提示"name字段缺失"。

修复方法

修改测试代码中的POST请求,将data参数替换为json参数,Flask测试客户端会自动将数据序列化为JSON并设置正确的Content-Type头:

def test_store_creation(client):
    """
    GIVEN a Store model
    WHEN a new Store is created
    THEN check the name field is defined correctly
    """
    access_token = create_access_token('admin')
    headers = {
        'Authorization': 'Bearer {}'.format(access_token)
    }
    # 使用json参数代替data参数
    response = client.post('/store', json={"name": "test_store"}, headers=headers)

    print(response.get_json())
    assert response.status_code == 201

额外注意事项

当前测试中创建JWT token时使用create_access_token('admin'),但你的JWT附加权限逻辑(add_claims_to_jwt)中仅当identity == 1时才会添加is_admin: True权限。如果后续需要测试管理员操作(比如删除商店),需要将token创建改为:

access_token = create_access_token(1)

或者调整add_claims_to_jwt的判断逻辑以匹配你的用户身份标识规则。

内容的提问来源于stack exchange,提问作者Jordan Petrov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 01:01:24