Home > database >  Cannot get data from request.get_json(force=True)
Cannot get data from request.get_json(force=True)

Time:12-06

import requests
import numpy as np
import json
from flask import Flask, request, jsonify

url = 'http://localhost:5000/api'

dat = np.genfromtxt('/home/panos/Manti_Milk/BigData/50_0_50_3.5_3-3.dat')
d1 = dat[:,0]

data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3": d1[3], "w4": d1[4],
          "w5": d1[5], "w6": d1[6], "w7": d1[7], "w8": d1[8], "w9": d1[9], "w10": d1[10],
          "w11": d1[11], "w12": d1[12], "w13": d1[13], "w14": d1[14], "w15": d1[15]}

jsondata = json.dumps(data, indent=4)


r = request.post(url, json = jsondata)

@app.route('/api',methods=['POST','GET'])
def predict():

    jsondata = request.get_json(force=True)
    dummy = json.loads(jsondata)    
    arr = np.fromiter(dummy.values(), dtype=float).reshape(16,1)

    return {"data": arr}

if __name__ == '__main__':
    app.run(port=5000, debug=True)

It returns Bad Request Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)

When setting force=False, returns "Null"

Any Help?

I have read several questoins/answers where it should work. But this is not the case!

CodePudding user response:

You do not need to decode json data after request.get_json(), it is already the Python dict. So the line dummy = json.loads(jsondata) is unnecessary.

@app.route('/api',methods=['POST','GET'])
def predict():
    jsondata = request.get_json(force=True)
    arr = np.fromiter(jsondata.values(), dtype=float)

EDIT:

First file - server.py:

import numpy as np
from flask import Flask, request


app = Flask(__name__)

@app.route('/api', methods=['POST', 'GET'])
def predict():
    jsondata = request.get_json(force=True)
    arr = np.fromiter(jsondata.values(), dtype=float).reshape(16, 1)
    print(arr)  # do whatever you want here
    return "1"


app.run(debug=True)

Second file - client.py:

import requests
import numpy as np

dat = np.genfromtxt('data.dat')
d1 = dat[:, 0]

data = {"w0": d1[0], "w1": d1[1], "w2": d1[2], "w3": d1[3], "w4": d1[4],
          "w5": d1[5], "w6": d1[6], "w7": d1[7], "w8": d1[8], "w9": d1[9], "w10": d1[10],
          "w11": d1[11], "w12": d1[12], "w13": d1[13], "w14": d1[14], "w15": d1[15]}

requests.post("http://127.0.0.1:5000/api", json=data)

Then execute them separately (from different console tabs):

At first, start the server in [1] tab:

$ python server.py

 * Running on http://127.0.0.1:5000
Press CTRL C to quit
 * Restarting with stat
 * Debugger is active!

And after that run request from client in another [2] tab:

$ python client.py

Then you will see desired output in server tab [1]:

[[2297.]
 [1376.]
 [1967.]
 [2414.]
 [2012.]
 [2348.]
 [2293.]
 [1800.]
 [2011.]
 [2340.]
 [1949.]
 [2015.]
 [2338.]
 [1866.]
 [1461.]
 [2158.]]
  • Related