微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

flask为什么要包装json?

flask为什么要包装json?

原文是这样解释的

on top of that it will delegate access to the current application’s json encoders and decoders for easier customization.

解释定制json输入输出.

一些源码

def jsonify(*args,**kwargs):
    if current_app.config['jsonify_prettyprint_regular'] or current_app.debug:
        indent = 2
        separators = (',',': ')
if args and <a href="https://www.jb51.cc/tag/kwargs/" target="_blank" class="keywords">kwargs</a>:
    raise typeerror('jsonify() behavior undefined when passed both args and <a href="https://www.jb51.cc/tag/kwargs/" target="_blank" class="keywords">kwargs</a>')
elif len(args) == 1:  # single args are passed directly to dumps()
    data = args[0]
else:
    data = args or <a href="https://www.jb51.cc/tag/kwargs/" target="_blank" class="keywords">kwargs</a>

return current_app.response_class(
    (dumps(data,indent=indent,sep<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>tors=sep<a href="https://www.jb51.cc/tag/ara/" target="_blank" class="keywords">ara</a>tors),'\n'),mimetype=current_app.con<a href="https://www.jb51.cc/tag/fig/" target="_blank" class="keywords">fig</a>['jsonify_mimetype']
)

def dumps(obj,kwargs):
_dump_arg_defaults(kwargs)
encoding = kwargs.pop('encoding',none)
rv = _json.dumps(obj,
kwargs)
if encoding is not none and isinstance(rv,text_type):
rv = rv.encode(encoding)
return rv

def loads(s,kwargs):
_load_arg_defaults(kwargs)
if isinstance(s,bytes):
s = s.decode(kwargs.pop('encoding',none) or 'utf-8')
return _json.loads(s,
kwargs)

可以看出

  • 对jsonify对返回值处理一下.

  • dumps则必要时转换了编码.

  • 同理loads则改要时解码了.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐