Flask开发API:接受不同'Content-Type'请求

使用Flask开发API时有时需要接收不同类型的"POST"请求,最常见的'Content-Type'有如下两种:

  • application/x-www-form-urlencoded
  • application/json

可以通过如下方法判断:

request.headers.get('Content-Type')

示例:

@api_v1.route('/user', methods=['POST'])
def new_user():
    #将接收到的参数统一保存在下面的dict中
    r = {} 
    # 判断'Content-Type'类型
    if request.headers.get('Content-Type') == 'application/x-www-form-urlencoded':
        r = request.form.to_dict()
    elif request.headers.get('Content-Type') == 'application/json':
        r = request.json
        
        ...
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容