如何修复pythonflas中的“Undefined is not JSON serializable”

2024-05-28 23:41:53 发布

您现在位置:Python中文网/ 问答频道 /正文

对于到中的给定用户输入

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

^{pr2}$

据我所知,当get_city_list函数被调用时,它将向python api发送user_input_country变量并获得其响应。然而,我一直得到“TypeError:Object of type Undefined is not JSON serializable”js和html在我打开html时似乎可以正常工作,但是当我运行服务器时,它会给我这个错误。在

我假设python代码有问题。我试过删除@应用程序路径(“/cities/…)但是它仍然给我同样的错误。我试着把返回的对象弄清楚,结果还是没找到。下面是我的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不把这当作一个注释,而是把它当作一个代码来读,所以当我试图用| tojson把它发送给js时,它不知道加拿大城市是什么地方,它总是给出错误。这是我的全部理解,如果我错了,请纠正我。最后,我干脆删除了这条评论,一切似乎都很好!在


Tags: 代码svgselfapiidtrueappcity

热门问题