Tornado 有正确的请求正文,但找不到正确的参数 [英] Tornado has correct request body, but cannot find correct arguments

查看:18
本文介绍了Tornado 有正确的请求正文,但找不到正确的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

制作一个非常简单的 Tornado 应用程序,但根据我对 Tornado 的理解,似乎不可能发生的事情正在发生.简而言之,我有以下 RequestHandler:

Making a pretty straightforward Tornado app, but something that seems impossible is happening based on my understanding of Tornado. In short I've got the following RequestHandler:

class CreateUserHandler(tornado.web.RequestHandler):
    def post(self):
        print self.request.body
        print self.get_body_argument("email")
        # Do other things

打印出来的内容如下:

{"email":"slater@indico.io","password":"password"}
WARNING:tornado.general:400 POST /user/create/ (::1): Missing argument email

因此电子邮件显然存在于正文中,但在尝试访问它时会引发 400.我可以手动解析请求正文,但 Tornado 的错误处理非常好,我希望尽可能避免重写它.

So email clearly exists in the body, and yet when trying to access it a 400 is raised. I could manually parse the request body, but Tornado's error handling is nice enough that I'd like to avoid rewriting it if possible.

所以,我的基本问题是这怎么可能?它正在打印正确的请求正文,然后以某种方式无法访问它刚刚打印的字典.

So, my basic question is how is this possible? It's printing the correct request body, and then is somehow unable to access the dictionary it just printed.

推荐答案

这是我添加到处理程序中的一个小辅助方法,以便将所有正文参数作为字典检索:

Here's a little helper method I've been adding to my handlers in order to retrieve all of the body arguments as a dict:

from tornado.web import RequestHandler
from tornado.escape import json_decode

class CustomHandler(RequestHandler):

    def get_all_body_arguments(self):
        """
        Helper method retrieving values for all body arguments.

        Returns:
            Dict of all the body arguments.
        """
        if self.request.headers['Content-Type'] == 'application/json':
            return json_decode(self.request.body)
        return {arg: self.get_body_argument(arg) for arg in self.request.arguments}

这篇关于Tornado 有正确的请求正文,但找不到正确的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆