You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过HTML按钮运行Python脚本(Flask/Django)实现股价刷新

Flask 实现方案

1. HTML 按钮与页面逻辑

在你的index.html中添加股价展示容器、刷新按钮,通过异步请求实现无刷新更新:

<!-- 股价展示区域 -->
<div id="stock-container">
  {% for stock in stocks %}
    <div class="stock-item">{{ stock.name }}: {{ stock.price }}</div>
  {% endfor %}
</div>

<!-- 刷新按钮 -->
<button id="refresh-btn">刷新股价</button>

<!-- 用jQuery实现异步请求(也可替换为原生JS) -->
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(function() {
  $('#refresh-btn').click(function() {
    // 发送GET请求到后端接口
    $.get('/refresh-stocks', function(data) {
      // 清空原有内容并渲染新数据
      let html = '';
      data.forEach(stock => {
        html += `<div class="stock-item">${stock.name}: ${stock.price}</div>`;
      });
      $('#stock-container').html(html);
    });
  });
});
</script>

2. Flask 后端代码

在主应用文件(如app.py)中添加异步接口,调用你的股价获取逻辑:

from flask import Flask, render_template, jsonify
# 导入你写的股价获取函数
from stock_fetcher import get_latest_stocks

app = Flask(__name__)

# 主页路由:初始化加载股价
@app.route('/')
def index():
    stocks = get_latest_stocks()
    return render_template('index.html', stocks=stocks)

# 异步刷新路由:返回最新股价的JSON数据
@app.route('/refresh-stocks')
def refresh_stocks():
    latest_stocks = get_latest_stocks()
    return jsonify(latest_stocks)

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

Django 实现方案

1. HTML 按钮与页面逻辑

在templates/index.html中添加对应元素和异步请求逻辑:

<!-- 股价展示区域 -->
<div id="stock-container">
  {% for stock in stocks %}
    <div class="stock-item">{{ stock.name }}: {{ stock.price }}</div>
  {% endfor %}
</div>

<!-- 刷新按钮 -->
<button id="refresh-btn">刷新股价</button>

<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script>
$(function() {
  $('#refresh-btn').click(function() {
    $.get('/refresh-stocks/', function(data) {
      let html = '';
      data.forEach(stock => {
        html += `<div class="stock-item">${stock.name}: ${stock.price}</div>`;
      });
      $('#stock-container').html(html);
    });
  });
});
</script>

2. Django 后端配置

2.1 视图函数(views.py)

from django.shortcuts import render
from django.http import JsonResponse
# 导入你的股价获取函数
from .utils import get_latest_stocks

def index(request):
    stocks = get_latest_stocks()
    return render(request, 'index.html', {'stocks': stocks})

def refresh_stocks(request):
    latest_stocks = get_latest_stocks()
    # safe=False用于返回列表格式的JSON
    return JsonResponse(latest_stocks, safe=False)

2.2 URL 路由配置(urls.py)

from django.contrib import admin
from django.urls import path
from your_app_name.views import index, refresh_stocks

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name='index'),
    path('refresh-stocks/', refresh_stocks, name='refresh-stocks'),
]

内容的提问来源于stack exchange,提问作者Tom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 02:45:42