测试用例如下
class AuthTest(AsyncTestCase):
@gen_test
def test_http_fetch(self):
client = AsyncHTTPClient(self.io_loop)
data = {
'type':'nomal',
'phone_num':'1322********',
'password':'******'
}
headers = {'Content-Type': 'application/json; charset=UTF-8'}
request = HTTPRequest(
url=BASE_URL + '/v1.0/auth',
method='POST',
body=json_encode(data),
headers=headers
)
response = yield client.fetch(request)
# Test contents of response
self.assertIn("ok", response.body)
但是无法通过测试,原因在于tornado 的get_body_argument(),get_argument()等函数并没有解析json的共轭呢过
以下是4.0下tornado.httputil中的部分代码
def parse_body_arguments(content_type, body, arguments, files, headers=None):
"""Parses a form request body.
Supports ``application/x-www-form-urlencoded`` and
``multipart/form-data``. The ``content_type`` parameter should be
a string and ``body`` should be a byte string. The ``arguments``
and ``files`` parameters are dictionaries that will be updated
with the parsed contents.
"""
if headers and 'Content-Encoding' in headers:
gen_log.warning("Unsupported Content-Encoding: %s",
headers['Content-Encoding'])
return
if content_type.startswith("application/x-www-form-urlencoded"):
try:
uri_arguments = parse_qs_bytes(native_str(body), keep_blank_values=True)
except Exception as e:
gen_log.warning('Invalid x-www-form-urlencoded body: %s', e)
uri_arguments = {}
for name, values in uri_arguments.items():
if values:
arguments.setdefault(name, []).extend(values)
elif content_type.startswith("multipart/form-data"):
try:
fields = content_type.split(";")
for field in fields:
k, sep, v = field.strip().partition("=")
if k == "boundary" and v:
parse_multipart_form_data(utf8(v), body, arguments, files)
break
else:
raise ValueError("multipart boundary not found")
except Exception as e:
gen_log.warning("Invalid multipart/form-data: %s", e)
可以看到并没有解析json
于是我们可以自己在基类中定义一个
class BassHandler(tornado.web.RequestHandler):
def get_json_argument(self, name, default = None):
args = json_decode(self.request.body)
name = to_unicode(name)
if name in args:
return args[name]
elif default is not None:
return default
else:
raise MissingArgumentError(name)
测试通过