gpt4 book ai didi

python - 使用 CSV 文件填充使用 Flask 显示最新天气的网页?

转载 作者:可可西里 更新时间:2023-11-01 12:49:57 31 4
gpt4 key购买 nike

我正在使用 JSON 获取一些天气数据并将此数据输出到 CSV 文件中,如下所示。

enter image description here

我想知道如何使用 Flask(已安装)在网络浏览器中显示我的 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()

这是我的编辑器的截图:

enter image description here

最佳答案

我认为您正在寻找 send_file() . Flask 端点看起来像这样:

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

关于python - 使用 CSV 文件填充使用 Flask 显示最新天气的网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17918312/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com