2
I am developing an application that makes predictions from models, and wanted to implement a feature that allows me to create new routes through a function.
config = json.loads(open('config.json').read())
def create_models(config):
for key, val in config.items():
globals()[key] = initialize_model(val)
@app.route('/predict1', methods=['GET', 'POST'])
def predict1():
if request.method == 'POST':
try:
information= request.data
except Exception as e:
print(e)
return abort(400, e)
try:
results_inventory = predict1.pred(information)
inventory = set_inventory(results_inventory)
return jsonify(inventory)
except Exception as e:
print(e)
return abort(500, e)
Everything is working as desired, config
loads my JSON with the necessary information, create_models
carries my models, predict1
receives the information and returns the results of the analysis.
I happen to have more than one model and wanted to provide a new route for each of them, here an example of my config.json
:
{
"predict1":
{
"model": "cfg/configurationfile1.txt",
"load": 115,
"threshold": 0.25,
},
"predict2":
{
"model": "cfg/configurationfile2.txt",
"load": 600,
"threshold": 0.10,
}
}
As I have two models inside my config.json
, I needed to create a new route manually, which is identical to the first one by changing only the places of the code where they appear predict1
for predict2
. Stayed like this:
@app.route('/predict1', methods=['GET', 'POST'])
def predict1():
if request.method == 'POST':
try:
information= request.data
except Exception as e:
print(e)
return abort(400, e)
try:
results_inventory = predict1.pred(information)
inventory = set_inventory(results_inventory)
return jsonify(inventory)
except Exception as e:
print(e)
return abort(500, e)
@app.route('/predict2', methods=['GET', 'POST'])
def predict2():
if request.method == 'POST':
try:
information= request.data
except Exception as e:
print(e)
return abort(400, e)
try:
results_inventory = predict2.pred(information)
inventory = set_inventory(results_inventory)
return jsonify(inventory)
except Exception as e:
print(e)
return abort(500, e)
There is a way to automate this route creation process, so the script itself generates a new route whenever a new configuration appears in my JSON?
I don’t know if I got your problem right. Do you want to read the JSON file at the beginning and then create the routes? Or after creating the routes, depending on what users call, create new routes based on what is in the JSON file?
– Victor Stafusa
Hello Victor, I wish to create routes from the contents of my JSON.
– Filipe Gonçalves
So the answer below should be what you want or something very close to it.
– Victor Stafusa