我有这段代码,该代码从某个开放的API获取值,并使用flask在html中显示空气质量。 我需要每5-10秒左右刷新一次值。
我使用线程每5秒返回一次值,但是它似乎仍然没有更新。如何在脚本和html文件中更新值?
总的来说,如果我调用一个变量,它是否可以一直工作到最开始并重新调用与其链接的所有其他函数和变量?
我只是从python和Web开发开始,所以这很令人困惑。
import json
import requests
from flask import Flask, render_template
import threading
station_name = '장량동'
gov_api_key = 'my_personal_key'
microdust_req_url = 'http://openapi.airkorea.or.kr/openapi/services/rest/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?stationName=%s&dataTerm=month&pageNo=1&numOfRows=10&ServiceKey=%s&ver=1.3&_returnType=json' %(station_name, gov_api_key)
dustdatatext = requests.get(microdust_req_url).text
dust_data = json.loads(dustdatatext)
my_city_data = dust_data['list'][0]
#Comprehensive Air-quality Index
cai = my_city_data['khaiValue']
def regular_run():
threading.Timer(5.0, regular_run).start()
return cai
#Flask webapp starts here
app = Flask(__name__)
@app.route('/')
def home():
return render_template('AQW.html', web_cai=cai)
if __name__=="__main__":
app.run(host='0.0.0.0')
这是HTML文件的内容。我编辑了这两个文件,将其发布到此处,以消除多余的内容,因为它不会添加到问题中。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Air Quality Widget</title>
<meta http-equiv="refresh" content="30" >
<!-- Bootstrap -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
@import url('https://fonts.googleapis.com/css?family=Roboto');
@import url('https://fonts.googleapis.com/css?family=Teko:700');
.font-roboto {
font-family: 'Roboto', sans-serif;
}
.font-teko {
font-family: 'Teko', sans-serif;
}
.good {
background-color: #0000FF
}
.moderate {
background-color: green
}
.bad {
background-color: yellow
}
.verybad {
background-color: #FF0000
}
.padding-bottom {
padding-bottom: 6px;
}
</style>
</head>
<body>
<div class="container-fluid font-roboto">
<div class="row justify-content-xl-center text-light">
<div class="col col-xl-5 col-1"></div>
<div class="col col-xl-2 col-10">
<div class="text-center padding-bottom">AIR QUALITY</div>
<div class= "text-center font-teko"> <!-- CAI number -->
<span class="display-1 {{web_background}}">
{{web_cai}}
</span>
</div>
</div>
</div>
</body>
</html>