Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 API-Call, Json und und Pygal
#1
Moin!
hiermit entwickle ich eine jkleine WebApp mit Flask und da ich eine API verwenden möchte für eine Visualisierung von Wetter-Daten (Name, temp_min und temp_max) habe ich den folgenden Fehler erhalten und mit Json zu arbeiten ist ganz neu für mich! Danke für Rückmeldung.
VG


KeyError
KeyError: 'name'

@app.route("/weather")
def weather():

    url = "https://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric&appid=get a Key"
    r = requests.get(url)
    data  = r.json()

    # Retrieve city names
    cities = []
    for city in data["name"]:
        cities.append(city["name"])

    # Retrieve temperatures
    min_temp, max_temp = [], []
    for elt in data["main"]:
        min_temp.append(elt["temp_min"])
        max_temp.append(elt["temp_max"]) 

    #Graph
    #Define simple style, added with pygal.style import
    style = LS("#333666", base_style=DS)

    chart = pygal.Bar(style=style, x_label_rotation=45, show_legend=False)
    chart.title = "Minimum and Maximum Temperatures"
    chart.x_labels = map(str, cities)
    chart.add("Minimum Temperature", min_temp)
    chart.add("Maximum Temperature", max_temp)

    chart = chart.render_data_uri()
    return render_template('weather.html', title='Call the API', chart = chart)
Output:
{% extends "layout.html" %} {% block title %}Call the API{% endblock %} {% block content %} <div class="content-section"> <h3>Visualization</h3> <!-- Don't forget the "|safe"! --> <div id="chart"> <embed type="image/svg+xml" src= {{ chart|safe }} /> </div> </div> {% endblock content %}
Json output
Output:
{ "cnt":3, "list":[ { "coord":{ "lon":37.62, "lat":55.75 }, "sys":{ "country":"RU", "timezone":10800, "sunrise":1567478244, "sunset":1567527668 }, "weather":[ { "id":802, "main":"Clouds", "description":"scattered clouds", "icon":"03d" } ], "main":{ "temp":23.64, "pressure":1017, "humidity":49, "temp_min":23, "temp_max":25 }, "visibility":10000, "wind":{ "speed":4, "deg":110 }, "clouds":{ "all":40 }, "dt":1567508823, "id":524901, "name":"Moscow" }, { "coord":{ "lon":30.52, "lat":50.43 }, "sys":{ "country":"UA", "timezone":10800, "sunrise":1567480483, "sunset":1567528836 }, "weather":[ { "id":800, "main":"Clear", "description":"clear sky", "icon":"01d" } ], "main":{ "temp":30.45, "pressure":1014, "humidity":40, "temp_min":29, "temp_max":31.67 }, "visibility":10000, "wind":{ "speed":3, "deg":300 }, "clouds":{ "all":0 }, "dt":1567508947, "id":703448, "name":"Kiev" }, { "coord":{ "lon":-0.13, "lat":51.51 }, "sys":{ "country":"GB", "timezone":3600, "sunrise":1567487750, "sunset":1567536278 }, "weather":[ { "id":804, "main":"Clouds", "description":"overcast clouds", "icon":"04d" } ], "main":{ "temp":18.83, "pressure":1024, "humidity":59, "temp_min":16.67, "temp_max":20.56 }, "visibility":10000, "wind":{ "speed":4.6, "deg":260 }, "clouds":{ "all":90 }, "dt":1567508964, "id":2643743, "name":"London" } ] }
Quote
#2
line 10 should be for city in data["list"]:

Note that you will need to change also line 17-19, in order to get min and max temp, but I will leave this to you for now
starter_student likes this post
Quote
#3
(Sep-03-2019, 03:59 PM)buran Wrote: line 10 should be for city in data["list"]:

Note that you will need to change also line 17-19, in order to get min and max temp, but I will leave this to you for now

Hey!
Thank you! I didn't see that :) ... anyway I've changed it but till got the same KeyError: "list"

    # Retrieve city names
    cities = []
    for city in data["list"]:
        cities.append(city["list"][1]["name"])

    # Retrieve temperatures
    min_temp, max_temp = [], []
    for elt in data["list"]:
        min_temp.append(elt["list"][0]["main"]["temp_min"])
        max_temp.append(elt["list"][0]["main"]["temp_max"])
Quote
#4
(Sep-04-2019, 07:32 AM)starter_student Wrote: anyway I've changed it but till got the same KeyError: "list"
it's on line 9 and 10 now. as I said you need to change these too.

city_names = []
min_temps = []
max_temps = []
for city in data['list']:
    city_names.append(city['name'])
    min_temps.append(city['main']['temp_min'])
    max_temps.append(city['main']['temp_max'])

print(city_names)
print(min_temps)
print(max_temps)
Output:
['Moscow', 'Kiev', 'London'] [23, 29, 16.67] [25, 31.67, 20.56]
starter_student likes this post
Quote
#5
(Sep-04-2019, 07:59 AM)buran Wrote:
(Sep-04-2019, 07:32 AM)starter_student Wrote: anyway I've changed it but till got the same KeyError: "list"
it's on line 9 and 10 now. as I said you need to change these too.

city_names = []
min_temps = []
max_temps = []
for city in data['list']:
    city_names.append(city['name'])
    min_temps.append(city['main']['temp_min'])
    max_temps.append(city['main']['temp_max'])

print(city_names)
print(min_temps)
print(max_temps)
Output:
['Moscow', 'Kiev', 'London'] [23, 29, 16.67] [25, 31.67, 20.56]

Thks you Hero

Please can you tell me what is wring with my code. Thks
Quote
#6
(Sep-04-2019, 08:09 AM)starter_student Wrote: what is wring with my code
the way you try to access different parts in the JSON object, e.g.
for city in data["list"]:
    cities.append(city["list"][1]["name"])
you loop over each element in data['list']. That is each city data being dict. Then you try to access city['list'] - there is no such key within city dict. Then you even try (not sure what) to use index as in list i.e. [1] or key=1 as in dict with int keys... again - city is not a list, nor there is key=1 in city dict

same apply to part where you try to get temps
starter_student likes this post
Quote
#7
(Sep-04-2019, 08:16 AM)buran Wrote:
(Sep-04-2019, 08:09 AM)starter_student Wrote: what is wring with my code
the way you try to access different parts in the JSON object, e.g.
for city in data["list"]:
    cities.append(city["list"][1]["name"])
you loop over each element in data['list']. That is each city data being dict. Then you try to access city['list'] - there is no such key within city dict. Then you even try (not sure what) to use index as in list i.e. [1] or key=1 as in dict with int keys... again - city is not a list, nor there is key=1 in city dict

same apply to part where you try to get temps


got it!. Thks
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)