from flask import Flask, render_template_string
app = Flask(__name__)
@app.route('/get-data')
def get_data():
# 读取data.txt文件的内容
with open(r'./2024/2/4/data.txt', 'r') as file:
data = file.read()
print(data)
# 返回数据的HTML表示
return render_template_string('<div>{{ data }}°C</div>', data=data)
@app.route('/')
def index():
string='''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>局部更新示例</title>
</head>
<body>
<div id="data-container">这里将显示data.txt的内容</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
const updateData = () => {
fetch('/get-data')
.then(response => response.text())
.then(html => {
document.getElementById('data-container').innerHTML = html;
})
.catch(error => console.error('Error:', error));
};
// 每5秒更新一次内容
setInterval(updateData, 1000);
});
</script>
</body>
</html>
'''
return string
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)