当用户插入国家名称时,我正在使用d3进行清理,并使用flask调用python api。首先,我的d3 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;
d3.select("#user_country").node().value = "";
clean_format(user_input_country, function(cleaned_input){
d3.json(`/cities/${cleaned_input}`)
.then(function(response){
console.log(response);
map = d3.select(".map-container")
map.selectAll("div").remove();
CreateMapTag();
setTimeout(function(){ markermap(response) }, 1000);
});
d3.json(`/nlp/${cleaned_input}`)
.then(function(summarized_text){
div = d3.select(".text-summarize");
div.selectAll("p").remove();
div.selectAll("h3").remove();
// receive summarized text from python
RenderTitle(cleaned_input);
RenderURL(cleaned_input);
RenderTextSummary(summarized_text);
});
})
});
来自d3.json(/cities/${cleaned_input}
)
.then(功能(响应)
它传递cleaned_input并从python获取结果,如下所示:
@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.
"""
with open('static/db/final_cities_countries.json') as f:
data = json.load(f)
# if data exists grab data, if not query again and store into db, then grab data
query = db.select([Aqi]).where(Aqi.Country == country)
result = db.engine.execute(query).fetchall()
if len(result) < 1:
list_of_cities = data[country]
for city in list_of_cities:
# store into db if aqi_call is ONLY successful with status:ok
if get_aqi(city) != None:
aqi_response = get_aqi(city)
time = aqi_response['data']['time']['s']
try:
lat = aqi_response['data']['city']['geo'][0]
lng = aqi_response['data']['city']['geo'][1]
except:
continue # skipping city that have no defined coordinates.
# Top 5 pollutants
try:
o3 = aqi_response['data']['iaqi']['o3']['v']
except:
o3 = -1
try:
so2 = aqi_response['data']['iaqi']['so2']['v']
except:
so2 = -1
try:
no2 = aqi_response['data']['iaqi']['no2']['v']
except:
no2 = -1
try:
pm25 = aqi_response['data']['iaqi']['pm25']['v'] #pm2.5
except:
pm25 = -1
try:
co = aqi_response['data']['iaqi']['co']['v']
except:
co = -1
# creating instance of Aqi class(row in MySQL table) and inserting into aqi table
insert_to_db = Aqi(country, city, aqi_response['data']['aqi'], o3, so2, no2, pm25, co, lat, lng, time)
db.session.add(insert_to_db)
db.session.commit()
# this time it will have more
query = db.select([Aqi]).where(Aqi.Country == country)
# result = [(id, country, city,...), (id, country, city,...), ...etc.]
result = db.engine.execute(query).fetchall()
# sending back list of dictionaries. [{id:x, country:y, city:z, etc...}, {},{},...]
return jsonify([dict(row) for row in result])
我最初使用的是d3.json v4,该版本未使用promise,但是阅读了有关该问题的信息并更改为v5,但仍然无法正常工作。