确保POST数据是有效的JSON

Dra*_*SAN 4 python json flask

我正在使用Python Flask开发JSON API.
我想要的是始终返回JSON,并显示一条错误消息,指出发生的任何错误.

该API也只接受POST正文中的JSON数据,但如果无法将数据作为JSON读取,则Flask默认返回HTML错误400.

优选地,我也希望不强迫用户发送Content-Type标题,并且如果rawtext内容类型,尽量尝试将主体解析为JSON.

简而言之,我需要一种方法来验证POST主体是否为JSON,并自己处理错误.

我已经阅读过关于添加装饰器来request做到这一点,但没有全面的例子.

Mar*_*ers 7

你有三个选择:

就个人而言,我可能会选择第二种选择:

from werkzeug.exceptions import BadRequest
from flask import json, Request, _request_ctx_stack


class JSONBadRequest(BadRequest):
    def get_body(self, environ=None):
        """Get the JSON body."""
        return json.dumps({
            'code':         self.code,
            'name':         self.name,
            'description':  self.description,
        })

    def get_headers(self, environ=None):
        """Get a list of headers."""
        return [('Content-Type', 'application/json')]


def on_json_loading_failed(self):
    ctx = _request_ctx_stack.top
    if ctx is not None and ctx.app.config.get('DEBUG', False):
        raise JSONBadRequest('Failed to decode JSON object: {0}'.format(e))
    raise JSONBadRequest()


Request.on_json_loading_failed = on_json_loading_failed
Run Code Online (Sandbox Code Playgroud)

现在,每次request.get_json()失败时,它都会调用您的自定义on_json_loading_failed方法并使用JSON有效负载而不是HTML有效负载引发异常.