Flask request.get_json()方法报错:AttributeError: 'NoneType' object has no attribute 'get'

一、问题描述:

请求方式:POST
报错提示

AttributeError: 'NoneType' object has no attribute 'get'

二、问题分析:

根据报错提示分析:空类型对象那个没有"get"属性
代码中打印 request.get_json() 函数的值,打印结果为None,没有取到值。再使用 request.data 函数取值,打印结果为byte类型数据。如下图:
测试结果
根据以上测试数据,可以判断问题就出在 request.get_json() 函数上。查看源代码:

# 源代码
def get_json(self, force=False, silent=False, cache=True):
    """Parse :attr:`data` as JSON.

    If the mimetype does not indicate JSON
    (:mimetype:`application/json`, see :meth:`is_json`), this
    returns ``None``.

    If parsing fails, :meth:`on_json_loading_failed` is called and
    its return value is used as the return value.

    :param force: Ignore the mimetype and always try to parse JSON.
    :param silent: Silence parsing errors and return ``None``
        instead.
    :param cache: Store the parsed JSON to return for subsequent
        calls.
    """

分析以上:原来 request.get_json() 函数默认情况下只对 mimetypeapplication/json 的请求可以正确解析,否则返回None

三、解决方法:

  1. http 请求增加header: Content-Type:application/json
  2. 使用 request.get_json(force=True) 忽略mimetype
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值