Tornado POST请求不检测json输入作为参数

时间:2015-08-27 21:02:32

标签: json post tornado

我编写了一个以json作为输入的服务。我使用网站hurl.it发送要检查的帖子请求。以下是我的代码段:

class BatchSemanticSimilarityHandler(tornado.web.RequestHandler):
 def post(self):
    self.set_header('Access-Control-Allow-Origin', '*')
    self.set_header('Access-Control-Allow-Credentials', 'true')
    self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
    self.set_header('Access-Control-Allow-Headers','Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token')
    data = json.loads(self.request.body)
    apikey = data["apikey"]
    try:
        UA = self.request.headers["User-Agent"]
    except:
        UA = "NA"
    if bool(usercoll.find_one({"apikey":apikey})) == True:
        sentence = data["sentence"]
        sentence_array = data["sentence_array"]
        n = data["num_of_results"]          
        if sentence is None or sentence_array is [] or apikey is None or n is None:
            self.set_status(200)
            output = {"error":[{"code":334,"message":"Bad Input data"}]}
            misscoll.insert({"apitype":"batchsemanticsimilarity","timestamp":datetime.datetime.now(), "ip":self.request.remote_ip, "useragent":UA, "uri":self.request.uri,"apikey":apikey, "output":output, "input":{"s1":sentence,"s2":sentence_array}})
            self.write(output)
            return
        results = nb.get_similar(sentence, sentence_array, apikey, n)
        print "results is",results
        output = {"similar_sentences": results, 'credits':'ParallelDots'}
        hitscoll.insert({"apitype":"batchsemanticsimilarity","timestamp":datetime.datetime.now(), "ip":self.request.remote_ip, "useragent":UA, "uri":self.request.uri,"apikey":apikey, "output":output, "input":{"s1":sentence,"s2":sentence_array}})
        self.write(output)
        return
    else:
        rejectcoll.insert({"apitype":"batchsemanticsimilarity","apikey":apikey,"timestamp":datetime.datetime.now(), "ip":self.request.remote_ip, "useragent":UA, "url":self.request.uri})
        self.write({"error":[{"code":333,"message": "Bad Authentication data"}]})
        return

我作为请求正文提供的json如下:

{
"sentence": "BJP leads in Bengaluru civic body`s poll, all eyes on JD(S)",
"sentence_array": [
    "Narendra Modi is the prime minister",
    "Sonia Gandhi runs Congress",
    "Sachin is a good batsman"
],
"apikey": "DyMe1gSNhvMV1I1b20a7KARYIwuQX5GAQ",
"num_of_results": 2
}

我已经在jsonlint上验证过这是一个有效的JSON。 但是,在发送请求时,它给出了以下错误:

  ValueError: No JSON object could be decoded

任何人都可以帮我解决这个问题!

1 个答案:

答案 0 :(得分:0)

您在POST请求中传递的JSON对象被编码到url中。 JSON库无法读取编码数据。因此,您需要首先解码URL。 可以使用python中的 urlparse 库来解码url。所以你需要这样的东西。         post_data=urlparse.parse_qsl(self.request.body)

根据您需要的最终格式阅读,urlparse.check中有各种方法this

如文档中所指定,您可以覆盖启用JSON解析的方法

def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None

检查this