簡體   English   中英

使用CSV文件填充使用燒瓶顯示最新天氣的網頁?

[英]Use a CSV file to populate a webpage that display the latest weather using flask?

我正在使用JSON獲取一些天氣數據,並將這些數據輸出到這樣的CSV文件中。

在此輸入圖像描述

我想知道如何使用Flask(已安裝)在Web瀏覽器中顯示我的CSV文件? 這是我的代碼到目前為止(它的工作)

#Source : http://www.wunderground.com/weather/api/d/docs?d=resources/code-samples
import urllib2
import json
import time
import csv
from datetime import datetime#set the time
from flask import Flask, send_file
app = Flask(__name__)
app.debug = True

def get_information(url):
  try:
    wunder_url_obj = urllib2.urlopen(url)
  except:
    print 'Could not open URL'
    return None

  else:
    now = datetime.now()
    current_year = now.year
    current_day = now.day
    current_month = now.month
    current_hour = now.hour
    current_minute = now.minute
    current_second = now.second
    json_string = wunder_url_obj.read()
    parsed_json = json.loads(json_string)
    temp_f = parsed_json['current_observation']['temp_f']
    weather = parsed_json['current_observation']['weather']
    date = str(now.month) + "/" + str(now.day) +  "/" + str(now.year) + " " +         str(now.hour) + ":" + str(now.minute) + ":" + str(now.second)
    now = datetime.now()    
    header = "Datetime,current condition,Temperature,\n" 

    with open('out.csv', 'a+') as f:
      f.seek(0, 2) # os.SEEK_END, on Windows file position set to 0 even in append mode.
      if f.tell() == 0:
        f.write(header)
      f.write(','.join([date, str(temp_f), weather]))
      f.write('\n')
      f.close()

get_information('http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json')

@app.route("/weather.csv")
def weather():
    url =     'http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json'
    get_information(url)
    return send_file("out.csv")

if __name__ == '__main__':
    app.run()  

這是我編輯的截圖:

在此輸入圖像描述

我想你正在尋找send_file() 燒瓶終點看起來像:

from flask import Flask, send_file
app = Flask(__name__)
app.debug = True

# Your get_information method

@app.route("/weather.csv")
def weather():
    url = "http://api.wunderground.com/api/8d3b5d3fa03ddb6f/conditions/weather/q/China/Beijing.json"
    get_information(url)
    return send_file("out.csv")

if __name__ == '__main__':
    app.run()   

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM