AttributeError:对象没有属性'json_args'

时间:2013-03-30 15:47:59

标签: python ios json tornado afnetworking

我正在尝试使用AFHTTPClient连接龙卷风服务器。这是我的客户代码:

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }


    [self setDefaultHeader:@"User-Agent" value:@"Client"];

    [self setDefaultHeader:@"Accept" value:@"application/json"];
    self.parameterEncoding = AFJSONParameterEncoding; 
    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

在服务器端,我将处理程序设置为如下:

class BaseHandler(tornado.web.RequestHandler):
    @property
    def db(self):
        return self.application.db

    def prepare(self):
        if self.request.headers.get("Content-Type") == "application/json":
            self.json_args = tornado.escape.json_decode(self.request.body)

然后构建了这个处理程序的子类:

class TimelineHandler(BaseHandler):
    def post(self):
        user_id = self.json_args.get("user_id")
        device_id = self.json_args.get("device_id")
        token = self.json_args.get("token")

        //do something with the request

        self.write(response)

但是当我运行此代码时,它失败并显示以下ERROR消息:

HTTPRequest(protocol='http', host=<CORRECT URL HERE>, method='POST', uri='CORRECT URL HERE', version='HTTP/1.0', remote_ip='127.0.0.1', body='{"user_id":1,"device_id":"b9af8d9039ec1e527fecca70caf486e1","token":"36c9a0fe-2c4f-4273-9e12-0f855e05de87"}', headers={'Content-Length': '107', 'Accept-Language': 'en;q=1, fr;q=0.9, de;q=0.8, ja;q=0.7, nl;q=0.6, it;q=0.5', 'Accept-Encoding': 'gzip, deflate', 'X-Scheme': 'http', 'Host': 'CORRECT URL HERE', 'Accept': 'application/json', 'User-Agent': 'Client', 'Connection': 'close', 'X-Real-Ip': '58.246.153.177', **'Content-Type': 'application/json**; charset=utf-8'})
    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1077, in _execute
        *self.path_args, **self.path_kwargs)
      File "/server.py", line 128, in post
        user_id = self.json_args.get("user_id")
    **AttributeError: 'TimelineHandler' object has no attribute 'json_args'**

奇怪的是,在请求标题中,它清楚地显示了'Content-Type':'application / json。那么为什么处理程序仍然没有属性'json_args'?

我正在使用龙卷风3.0。

如果你能给我任何建议,非常感谢你。

1 个答案:

答案 0 :(得分:1)

事实证明这是由Content-Type设置引起的:

在BaseHandler上:

def prepare(self):
         if self.request.headers.get("Content-Type") == "application/json":
             self.json_args = tornado.escape.json_decode(self.request.body)

但实际上在请求标题中:

'Content-Type':'application / json;字符集= UTF-8'

此字符串完全不匹配。但即使在从客户端设置Content-Type =“application / json”之后,字符串也会再次附加“; charset = utf-8”。我修复此问题的唯一方法是将basehandler代码更改为:

def prepare(self):
         if self.request.headers.get("Content-Type") == "application/json; charset=utf-8":
             self.json_args = tornado.escape.json_decode(self.request.body)

它解决了我的问题。但是,还有人知道“charset = utf-8”来自哪里?它是由AFNetworking自动设置的吗?

谢谢!