简体   繁体   中英

Flask API returns {"locations":null} instead returning of locations

I have attached 2 separate codes one is for the flask app server.py and the second is for loading pickles files: util.py . util.py has 3 functions,

  • First hello() returning message successfully
  • and the second get_location_names() not returning the location, it is supposed to return the location

This is my server.py which is a flask app.

from flask import Flask, request, jsonify

app = Flask(__name__)

import util

@app.route('/')

def hello():

   response = jsonify({
       'mesg' : util.hello()
       })

   response.headers.add('Access-Control-Allow-Origin','*')

   return response

@app.route('/get_location_names')

def get_location_names():

    response = jsonify({
        'locations' : util.get_location_names()
        })
    response.headers.add('Access-Control-Allow-Origin','*')
    
    return response   


@app.route('/predict_home_price',methods=['POST'])

def predict_home_price():

    total_sqft = float(request.form['total_sqft'])
    location = request.form['location']
    bed = int(request.form['bed'])
    bath = int(request.form['bath'])
    
    response = jsonify({
        'estimated_price' : utils.get_estimated_price(location, total_sqft, bed, bath)
    })

    response.headers.add('Access-Control-Allow-Origin','*')
    return response
    
if __name__ == '__main__':
    print('Starting Python Flask Server')
    app.run()

And here is my utils for loading pickles files

import json

import pickle

import numpy as np

__location = None

__data_columns = None

__model = None

def hello():

   return "Hello World! This is Python Flask Server...........!"

def get_estimated_price(location,sqft,bed,bath):

    try:
        loc_index = __data_columns.index(location.lower())
    except:
        loc_index = -1
    x = np.zeros(len(__data_columns))
    x[0] = sqft
    x[1] = bath
    x[2] = bed
    if loc_index >= 0:
        x[loc_index] = 1   
    return round(__model.predict([x])[0],2)

def get_location_names():

    global __location
    return __location

def load_saved_artifacts():

    print('Loading Saved Artifacts....Start')
    
    global __data_columns
    global __location
    with open('./artifacts/columns.json','r') as col:
        __data_columns = json.load(col)['my_data_columns']
        __location = __data_columns[3:]
        
    global __model    
    with open('./artifacts/House_Prediction_Price.pickle','rb') as my_model:
        __model = pickle.load(my_model)
    print('Loading saved artifacts is done...!')

if __name__ == '__main__':
    
    load_saved_artifacts()
    print(get_location_names())
    print(get_estimated_price('1st block jayanagar',1000,3,3))
    print(get_estimated_price('1st block jayanagar',1000,2,2))
    print(get_estimated_price('kodihalli',1000,2,2))
    print(get_estimated_price('Ejipura',1000,2,2))

The code is importing the module utils.py from another module server.py , then the __name__ variable will be set to that module's name, and hence your load_saved_artifacts() in if block won't execute. Try adding load_saved_artifacts() outside of if block, and check for the _location in get_location_names() In your get_location_names() check the value for __location

#.... <utils.py> other lines
def get_location_names():

    global __location
    if __location is None:
         load_saved_artifacts() # Doing this will make first request dependent on the execution time of this function call 
    return __location

load_saved_artifacts() # you can call your function here so that it will execute when your module is imported 
if __name__ == "__main__":
     #....
     #other lines

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM