steff_bdh
steff_bdh

Reputation: 1188

How to get Json object from GETrequest in FLASK

My server is flask, my client is javascript, i'm using jquery - ajax to send data to the server. I am able to get JSON objects from a POST request but unable to do so with a GET.

request from Javascript Client:

$.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 to handle request in flask:

@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

Output from print request:

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

Output from print json_str,' <--- json data'

<--- json data

Stacktrace for server:

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")

Upvotes: 1

Views: 1548

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121894

You need to extract the query string; you can use the request.query_string attribute to access it; you'll have to manually unquote it:

From urllib import unquote

json_str = unquote(request.query_string)

Your view then outputs:

<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

The request.get_data() method can only be used to access the request body, and a GET request never has a body.

If your data consists just of key-value pairs it may be easier just to stick to form-encoding those however and stick with Flask's request.args functionality instead of bothering with JSON here.

Upvotes: 3

Related Questions