简体   繁体   中英

How to fix “Undefined is not JSON serializable” in python flask

for given user input in to

   <button class="btn-search" type="submit" id="submit">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                  <path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>
                </svg>
              </button>

using Javascript d3 I select the input and process some cleaning and trying to send it to python where it will call an api for me. First of all this is my javascript code

var country_search = d3.select("#submit")

country_search.on("click", function(){
    d3.event.preventDefault();

    var user_input_country = d3.select("#user_country").node().value;
    const splitted = user_input_country.split(" ");
    d3.select("#user_country").node().value = "";

    // if no space in country name
    if (splitted.length === 1){
        user_input_country = user_input_country.charAt(0).toUpperCase() + user_input_country.slice(1).toLowerCase()
    }
    // if space --> titlecase all other than of/and,...etc.
    else{
        for (var i=0; i <splitted.length; i++) {
            // titlecase except for the word "of"
            if (splitted[i] != "of" && splitted[i] !="and"){
                splitted[i] = splitted[i].charAt(0).toUpperCase() + splitted[i].slice(1).toLowerCase()
            }
        }
        user_input_country = splitted.join(" ")
    }

    get_city_list(user_input_country);
})

function get_city_list(country){
    console.log(country);
    d3.json(`/cities/${user_input_country}`).then(function(response){
        console.log(`successfuly got python api ${response}`)
})
};

From my understanding when get_city_list function is called it will send user_input_country variable to python api and get its response. However I keep on getting "TypeError: Object of type Undefined is not JSON serializable" js and html seems to work fine when I simply open html however when I run the server it gives me this error.

I am assuming there is something wrong in python code. I've tried deleting @app.route("/cities/....) however it still gives me the same error. I've tried to jsonify returning object and still no luck. here is my python code:

app = Flask(__name__)

app.config["SQLALCHEMY_DATABASE_URI"] = 'mysql+pymysql://root:Gksmf12#@localhost:3306/aqi_db'

db = SQLAlchemy(app)

class Aqi(db.Model):
    __tablename__ ='aqi_info'
    id = db.Column('id', db.Integer, primary_key=True)
    Countries = db.Column(db.String(30), unique=True)
    Cities = db.Column(db.String(30), unique=True)
    aqi = db.Column(db.Integer)
    # declare how query is outputted.
    def __repr__(self):
        return f"Aqi('{self.Countries}', '{self.Cities}', '{self.aqi}')"

@app.route("/")
def index():
    """Return the homepage."""
    return render_template("index.html")


@app.route("/cities/<country>")
def cities(country):
    """ for given country
    1. get list of cities from json file.
    2. loop through each city and call api to get AQI data.
    3. store into db
    4. return {city:[], aqi:[], lat_lng:[a,b]} so heat map can be made.
    """
    print(country)
    pass

if __name__ == "__main__":
    app.run(debug=True)

Edit: I've tried testing bit by bit and when I render different html as soon as server load it works fine. It must be problem in html however cannot find it nor understand why.

Solution: I've finally solved it. From most unexpected place, in html. I had a code that have been commented out


  <!-- received data from python and putting in a script therefore js can use it. -->
  <!-- <script>
      var canadian_cities = {{canada_cities|tojson}};
      var pop = {{pop|tojson}};
  </script> -->

however it seemed like jinja does not consider this as a comment however reads it as a code therefore it didn't know what canada_cities was therefore when I was trying to send it to js using |tojson it kept on giving that error. This is all my understanding, please correct me if I am wrong. Finally I've simply deleted that comment and everything seems to work fine!

  1. Your function cities returns nothing.
  2. For Countries and Sities you need use relationship, I think so. https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#one-to-many
  3. Use jsonify for serialization (from flask import jsonify)

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