【问题标题】:How to fix "Undefined is not JSON serializable" in python flask如何在 python 烧瓶中修复“未定义不是 JSON 可序列化”
【发布时间】:2019-11-29 06:03:26
【问题描述】:

对于给定的用户输入

   <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>

使用 Javascript d3 我选择输入并处理一些清理并尝试将其发送到 python 它将为我调用 api。首先这是我的javascript代码

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}`)
})
};

据我了解,当调用 get_city_list 函数时,它会将 user_input_country 变量发送到 python api 并得到它的响应。但是我不断收到“TypeError:未定义类型的对象不是 JSON 可序列化”js 和 html 似乎在我简单地打开 html 时工作正常但是当我运行服务器时它给了我这个错误。

我假设 python 代码有问题。我试过删除 @app.route("/cities/....) 但它仍然给我同样的错误。我试图 jsonify 返回对象但仍然没有运气。这是我的 python 代码:

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)

编辑:我尝试过一点一点的测试,当我在服务器加载后立即渲染不同的 html 时,它工作正常。它一定是 html 中的问题,但是找不到它也不明白为什么。

解决方案:我终于解决了。从最意想不到的地方,在 html 中。我有一个代码被注释掉了


  <!-- 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> -->

然而 jinja 似乎并不认为这是一条评论,而是将其作为代码读取,因此它不知道 canada_cities 是什么,因此当我尝试使用 |tojson 将它发送到 js 时,它一直给出该错误。以上是我的全部理解,如有错误请指正。最后,我只是删除了该评论,一切似乎都正常!

【问题讨论】:

  • 看看您可能将undefined 对象序列化为JSON 的位置。这就是错误告诉你的。也许如果对象是undefined,您希望将其设为null,以便序列化按预期工作。
  • 是不是因为我在javascript中使用了带有变量“i”的for循环?

标签: javascript python json flask


【解决方案1】:
  1. 您的功能城市不返回任何内容。
  2. 对于需要使用关系的国家和地区,我认为是这样。 https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#one-to-many
  3. 使用jsonify进行序列化(从flask导入jsonify)

【讨论】:

  • 不是这样,我已经编辑了解决方案。看看吧。
猜你喜欢
  • 1970-01-01
  • 2020-08-10
  • 2014-11-25
  • 2023-02-09
  • 1970-01-01
  • 2018-07-28
  • 2020-11-06
  • 2019-12-05
  • 1970-01-01
相关资源
最近更新 更多