我正在使用 flask-restful 的请求解析器来解析通过 POST 请求发送的 JSON 中的参数。
该请求在使用 Postman 工具时运行良好。但从 android 发出请求时返回 500 响应。
我的资源类是:
class QuestionIgnore(restful.Resource):
@login_required
def post(self):
q_ignore_parser = reqparse.RequestParser()
q_ignore_parser.add_argument('question_id', type=str, location='json', required=True)
print request.json
args = q_ignore_parser.parse_args()
#do something with the database
return {'question_id':args['question_id']}
下面应该是对该资源的完全有效的请求:
Content-Length: 48
User-Agent: Dalvik/1.6.0 (Linux; U; Android 4.4.2; Nexus 4 Build/KOT49H)
Connection: close
Host: myhost.com
X-Forward-For: 111.111.111.111
X-Deviceid: xxxxxxxxxxxxxxxx
X-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Content-Type: application/json
Accept-Encoding: gzip
{"question_id":"somerandomstring123456789"}
该请求在使用邮递员测试 API 时完美运行,但从 android 应用程序中发送请求时,服务器返回 500 响应代码。发送此请求时,我得到以下回溯:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 257, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 257, in error_router
return self.handle_error(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 397, in wrapper
resp = resource(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask/views.py", line 84, in view
return self.dispatch_request(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/__init__.py", line 487, in dispatch_request
resp = meth(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/flask_login.py", line 764, in decorated_view
return func(*args, **kwargs)
File "/home/ubuntu/MY_PROJECT/api/resources.py", line 617, in post
args = q_ignore_parser.parse_args()
File "/usr/local/lib/python2.7/dist-packages/flask_restful/reqparse.py", line 212, in parse_args
namespace[arg.dest or arg.name] = arg.parse(req)
File "/usr/local/lib/python2.7/dist-packages/flask_restful/reqparse.py", line 131, in parse
values = [source.get(name)]
AttributeError: 'unicode' object has no attribute 'get'
我一开始以为是 JSON 格式不正确,但是 android 发送的 JSON 是完美的,和邮递员的请求一样。内容类型标头也完好无损。事实上,如果请求格式不正确,服务器应该返回 400 响应而不是 500。
任何想法可能是什么原因造成的?