[flask小坑] request.json 无法获取请求body的json数据

写接口自动化测试的时候,发现用httpie发送带有put请求,flask后端api可以获取到json数据,而我用robotframework发送的请求就不行,flask的 request.json 获取到的数据为 None

怎么办?查文档,看代码呗

代码 https://github.com/pallets/flask/blob/master/flask/wrappers.py#L53:22

    @property
    def json(self):
        """This will contain the parsed JSON data if the mimetype indicates
        JSON (:mimetype:`application/json`, see :meth:`is_json`), otherwise it
        will be ``None``.
        """
        return self.get_json()

    def _get_data_for_json(self, cache):
        return self.get_data(cache=cache)

    def get_json(self, force=False, silent=False, cache=True):
        """Parse and return the data as JSON. If the mimetype does not
        indicate JSON (:mimetype:`application/json`, see
        :meth:`is_json`), this returns ``None`` unless ``force`` is
        true. 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.json 调用的是 request.get_json() 这个函数,但是 get_json 这个函数默认情况下只对 mime 为 application/json 的请求可以正确解析。

所以解决办法是

  • http 请求增加 Content-Type:application/json header
  • 或者 使用 request.get_json(force=True) 忽略mimetype

还是要仔细看文档呀,。。

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值