如何从FLASK中的GET请求获取Json对象

时间:2015-04-15 20:55:52

标签: jquery python ajax json flask

我的服务器是烧瓶,我的客户端是javascript,我正在使用jquery - ajax将数据发送到服务器。我可以从POST请求中获取JSON对象,但无法通过GET获取。

来自Javascript客户端的请求:

$.ajax({type: 'GET',
        url: "/checkForTrain",
        data: jsonObj,
        success: function(response){
            response = JSON.parse(response)
            if(response['status']==='success')
                postDataset(data)
            else
                handleError(data)
        },
        error :   function(response){
            console.log(response)
        }
    })

url处理烧瓶中的请求:

@app.route('/checkForTrain',methods=['GET','OPTIONS'])
def checkForTrain():
    print request
    json_str=u''+str(request.get_data())
    print json_str,' <--- json data'
    dataSearch = json.loads(json_str)
    print dataSearch,' <--- dictionary'
    obj = dbWrapper.checkForTrain(dataSearch['name'],dataSearch['type'])
    return obj

打印请求的输出:

<Request 'http://localhost:5000/checkForTrain?{"name":"lel","technique":"regression"}' [GET]>

来自print json_str的输出,'&lt; --- json data'

<--- json data

服务器的Stacktrace:

Traceback (most recent call last):
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/lib/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/adminuser/Desktop/Github/DataMining/DataMiningProject/app/routes.py", line 53, in checkForTrain
    dataSearch = json.loads(json_str)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
    raise ValueError("No JSON object could be decoded")

1 个答案:

答案 0 :(得分:3)

您需要提取查询字符串;您可以使用request.query_string attribute来访问它;你必须手动unquote它:

From urllib import unquote

json_str = unquote(request.query_string)

您的视图会输出:

<Request 'http://localhost:5000/checkForTrain?{"name":"lel","technique":"regression"}' [GET]>
{"name":"lel","technique":"regression"}  <--- json data
{u'technique': u'regression', u'name': u'lel'}  <--- dictionary

request.get_data() method只能用于访问请求正文GET请求永远不会有正文。

如果您的数据只包含键值对,那么可能更容易坚持使用表单编码,但坚持使用Flask的request.args功能,而不是在这里使用JSON。