This is my first time working on webserver, and I'm writing restful get request using flask to pass parameters to the predictive model that I built.
from flask import Flask, Response
app = Flask(__name__)
api = Api(app)
class AST(Resource):
def get(self):
args = request.args
x1 = args['key1']
x2 = args['key2']
X = [[x1, x2]]
x = load_scaler.transform(X)
y_predict = load_model.predict(x)
y_predict = load_model.predict(np.array(x)).tolist
time = [{'predection':y_predict}]
return Response (json.dumps(time), mimetype='application/json')
api.add_resource(AST, '/start_time')
if __name__ == '__main__':
app.run
When I ran the code, it gave me the error:
The traceback shows
File "/Users/123/Documents/123/webserver/predictionast.py", line 60, in get
return Response (json.dumps(time), mimetype='application/json')
File "/Users/123/opt/anaconda3/lib/python3.7/json/__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "/Users/123/opt/anaconda3/lib/python3.7/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/Users/123/opt/anaconda3/lib/python3.7/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/Users/123/opt/anaconda3/lib/python3.7/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type builtin_function_or_method is not JSON serializable
y_predict is array
This error as says "object of built in types are not JSON serializable" occurs when you try to pass python built in method or attributes to the json.loads or dumps methods. It fails to serialize the internal types of python methods. For example:
json_1 = {"time": datetime.now}
json_2 = {"time": str(datetime.now)}
print(json.loads(json_2))
print(json.loads(json_1))
The json_1 object will fail when you try to print it while serialzing as it uses the internal bulit in python method. On the other hand the json_2 would be serialized and printed as it uses the well known data type to JSON - String.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With