关于python:flask请求args解析器错误浏览器(或代理)发送了该服务器无法理解的请求

flask request args parser error The browser (or proxy) sent a request that this server could not understand

使用test_client并发送如下请求:

1
2
3
4
5
6
app = Flask(__name__)
client = app.test_client()

headers = {'content-type': 'application/json', 'Authorization': u'Bearer fake_token_123'}
params = {'dont_care': True}
client.get(??'/my_route/123', query_string=params, headers=headers)

我的路线是

1
2
3
4
5
6
7
8
class MyController(Resource):

    def get(self, id):
        parser = reqparse.RequestParser()
        parser.add_argument('currency', type=str, default='USD', help="help text")

        args = parser.parse_args()
        currency_from_params = args.currency

parser.parse_args()失败

1
The browser (or proxy) sent a request that this server could not understand

从标题中删除'content-type': 'application/json'时,它可以工作。

我不了解这种行为,如果没有不雅致的try, expect,如何避免这种行为。

谢谢你的帮助


您已经找到了解决方法:如果您不发布JSON,请不要发送content-type: application/json。 您无法使用GET发送JSON,即使可以(或正在使用POST),也必须先使用json.dumps(data)编码JSON。