2016-12-08 10 views
1

pythonanywhereフラスコアプリケーションを使用して、簡単な3日間の天気予報データを表示しようとしています。ここに私のコードは、これまでのところです:フラスコを使用して辞書からデータを表示する、pythonanywhere

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) 

、ここでは簡単な「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> 

私はこの仕事を得るように見えることはできません。私はそれがデータのフォーマットと関係があると思う?それはむしろインポートされる別のファイルであるべきですか?

+0

あなたは問題が何であるかは言いませんが、私はそれがどこにもないぶらぶらしたリターンに関係していると思われます。 – polku

答えて

1

このように、あなたのビュー関数内でのpythonロジックを入れて:

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

APIのデータを見ることで、私はあなたの{{ value[1] }}はまだタプルだと思いますが、これをレンダリングするテンプレートに{{ value[1][0] }}, {{ value[1][1] }}のようなものが必要になる場合がありますので、データ。

pythonにprintステートメントを追加して、データ構造の解析方法をデバッグします。

関連する問題