在Flask POST请求中,提交数据方式(Conten-Type)有很多,比如:application/json,multipart/form-data等,而每种提交方式对应的取值方式也是不同的,
比如,如果提交方式为application/json,取值方式为:
request.get_json()
但是如果提交方式为multipart/form-data,取值方式为:
request.form
这样就限定了在写api的时候需要让调用者指定用某一种固定的提交方式,极为不方便,也容易出错
会DjangoRestFramework的人应该知道,Request 对象的data可以取出不同提交方式的数据,只因为DjangoRestFramework对Django原生的Request对象进行的再次封装,把这些POST请求的数据都放在在data里面,而Flask 没有对此进行封装,下面是模仿django rest 的方式把常用的提交方式的数据返回
from flask_restful import request def get_datas(): headers = request.headers print(‘headers:‘, headers) content_type = headers.get(‘Content-Type‘) if content_type == ‘application/x-www-form-urlencoded‘: print(‘x-www-form-urlencoded:‘, request.form) return request.form if content_type == ‘application/json‘: print(‘json:‘, request.get_json()) return request.get_json() content_type_list = str(content_type).split(‘;‘) if len(content_type_list) > 0: if content_type_list[0] == ‘multipart/form-data‘: print(‘multipart/form-data:‘, request.form) return request.form
当然 from flask_restful import request 也可以换成from flask import request
以上代码和文字均为自己的经验所写,可能存在很多缺陷,不喜勿喷,欢迎留言交流,共同学习,共同进步
原文:https://www.cnblogs.com/gongnanxiong/p/11733537.html