测试前端

from flask import Flask, render_template_string, request, jsonify
import requests

app = Flask(__name__)

# 请替换成你自己的 API Key
WEATHER_API_KEY = "YOUR_WEATHER_API_KEY"

# 假设这里是 minicom 保存 Pico 数据文件的路径,请根据实际修改
PICO_LOG_FILE = "/home/rui/learn/minicom.cap"

def get_log_tail(filename, tail_lines=10):
    try:
        with open(filename, 'r') as f:
            lines = f.read().splitlines()[-tail_lines:]
    except Exception as e:
        lines = [f"读取日志出错:{e}"]
    return lines

@app.route('/')
def index():
    html_content = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Python前端页面</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    </head>
    <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="/">首页</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav">
                    <li class="nav-item active">
                        <a class="nav-link" href="/weather">天气 <span class="sr-only">(当前)</span></a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="#">田地数据图表</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="http://localhost:8080">AI询问</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/realtime">Pico数据</a>
                    </li>
                </ul>
            </div>
        </nav>
        <div class="container mt-4">
            <h1>欢迎使用 Python 创建前端页面!</h1>
        </div>
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    </body>
    </html>
    """
    return render_template_string(html_content)

@app.route('/weather', methods=['GET'])
def weather():
    # 默认城市为北京,可通过 URL 参数 ?city=城市名 动态查询
    city = request.args.get("city", "Beijing")
    api_url = f"http://api.weatherapi.com/v1/current.json?key={WEATHER_API_KEY}&q={city}&lang=zh"
    try:
        response = requests.get(api_url)
        weather_data = response.json()
    except Exception as e:
        weather_data = {"error": str(e)}
    
    html_content = """
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>天气信息 - {{ city }}</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    </head>
    <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="/">首页</a>
        </nav>
        <div class="container mt-4">
            <h1>天气信息</h1>
            <h3>城市:{{ city }}</h3>
            {% if weather %}
                <p>温度:{{ weather.current.temp_c }} °C</p>
                <p>状态:{{ weather.current.condition.text }}</p>
                <img src="https:{{ weather.current.condition.icon }}" alt="天气图标">
            {% else %}
                <p>无法获取 {{ city }} 的天气信息.</p>
            {% endif %}
            <form class="mt-4" method="get" action="/weather">
                <div class="form-group">
                    <label for="city">查询其他城市:</label>
                    <input type="text" class="form-control" id="city" name="city" placeholder="输入城市名">
                </div>
                <button type="submit" class="btn btn-primary">查询</button>
            </form>
        </div>
        <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    </body>
    </html>
    """
    if "error" in weather_data:
        weather = None
    else:
        weather = weather_data
    return render_template_string(html_content, city=city, weather=weather)

# 接口:返回 Pico 数据日志的最新几行
@app.route('/pico-data', methods=['GET'])
def pico_data():
    lines = get_log_tail(PICO_LOG_FILE, tail_lines=10)
    return jsonify(lines=lines)

# 页面:通过轮询实时展示 Pico 数据
@app.route('/realtime')
def realtime():
    html_content = """
    <!DOCTYPE html>
    <html>
    <head>
         <meta charset="utf-8">
         <title>Pico实时数据</title>
         <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
         <script>
             // 每隔2秒获取一次最新数据
             function fetchData(){
                 fetch('/pico-data')
                   .then(response => response.json())
                   .then(data => {
                      let content = data.lines.join("<br>");
                      document.getElementById("data").innerHTML = content;
                   })
                   .catch(err=>console.error(err));
             }
             setInterval(fetchData, 2000);
         </script>
    </head>
    <body>
         <nav class="navbar navbar-expand-lg navbar-light bg-light">
             <a class="navbar-brand" href="/">首页</a>
         </nav>
         <div class="container mt-4">
             <h1>Pico实时数据</h1>
             <div id="data" class="border p-3" style="height:300px; overflow:auto;">正在加载数据...</div>
         </div>
         <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
         <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    </body>
    </html>
    """
    return render_template_string(html_content)

if __name__ == '__main__':
    # 建议在局域网内访问时使用 host="0.0.0.0"
    app.run(debug=True, host="0.0.0.0")
  

 

posted @ 2025-02-24 08:47  王翔9980  阅读(14)  评论(0)    收藏  举报