Search code examples
pythonflaskjinja2pythonanywhere

Displaying data from dictionary using flask, pythonanywhere


I am trying to display some simple 3 day weather forecast data using pythonanywhere flask app. Here is my code so far:

from flask import Flask, render_template
import requests
from collections import defaultdict


app = Flask(__name__)

r = requests.get("http://api.wunderground.com/api/mykey/forecast/q/SouthAFrica/Stellenbosch.json")
data = r.json()
weather_data = defaultdict(list)

counter = 0
for day in data['forecast']['simpleforecast']['forecastday']:
    date= day['date']['weekday'] + ":"
    cond=  "Conditions: ", day['conditions']
    temp= "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C"


    counter = counter + 1

    weather_data[counter].append(date)
    weather_data[counter].append(cond)
    weather_data[counter].append(temp)

return weather_data

@app.route('/')
def home():
    return render_template('home.html', weather_data=weather_data)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=5000)

and here is the simple 'home.html':

<table>
{% for key,value in weather_data.items() %}
    <tr>
        <td>{{value[1]}}</td>
        <td>{{value[2]}}</td>
        <td>{{value[3]}}</td>
        <td>{{value[4]}}</td>
    </tr>
{% endfor %}
</table>

I can't seem to get this to work. I suspect it is something to do with the format of the data? Should it rather be a separate file that is imported?


Solution

  • Put the python logic within your view function, like this:

    @app.route('/')
    def home():
        r = requests.get("http://api.wunderground.com/api/key/forecast/q/SouthAfrica/Stellenbosch.json")
        data = r.json()
        weather_data = defaultdict(list)
    
        counter = 0
        for day in data['forecast']['simpleforecast']['forecastday']:
            date = day['date']['weekday'] + ":"
            cond = "Conditions: ", day['conditions']
            temp = "High: ", day['high']['celsius'] + "C", "Low: ", day['low']['celsius'] + "C"
    
            counter += 1
    
            weather_data[counter].append(date)
            weather_data[counter].append(cond)
            weather_data[counter].append(temp)
    
        return render_template('home.html', weather_data=weather_data)
    

    By looking at the API data I think your {{ value[1] }} is still a tuple so you might need something like {{ value[1][0] }}, {{ value[1][1] }} in your template to render this data.

    Add print statements to your python to debug how to parse the data structure.