首页 > 解决方案 > 如何在不刷新烧瓶项目页面的情况下更新值

问题描述

所以我有一个网站,它显示视频游戏中的物品价格,目前我有一个“自动刷新”脚本,每 5 秒刷新一次页面,但每次搜索产品时有点烦人,它删除您的搜索,因为页面刷新。我希望它在不为用户刷新页面的情况下更新表中的数字。

我在 javascript 中读到了一些关于“更新 DOM”的内容,但在这里没有得到它是我网站的链接

这是我的python代码:

@app.route('/bprices', methods=['GET'])
def bPrices():
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=[cannot show]').json()

    products = [
        {
            "id": product["product_id"],
            "sell_price": product["sell_summary"][:1],
            "buy_price": product["buy_summary"][:1],
            "sell_volume": product["quick_status"]["sellVolume"],
            "buy_volume": product["quick_status"]["buyVolume"],
        }
        for product in f["products"].values()
    ]
    return render_template("bprices.html", products=products)

这是我的 HTML 代码:

<div class="container">
  <div class="search_div">
    <input
      type="text"
      onkeyup="myFunction()"
      id="myInput"
      title="Type in a product"
      class="search-box"
      placeholder="Search for a product..."
    />
    <button class="search-btn"><i class="fas fa-search"></i></button>
  </div>

  <table
    id="myTable"
    class="table table-striped table-bordered table-sm table-dark sortable"
    cellspacing="0"
  >
    <thead>
      <tr>
        <th aria-label="Product Name" data-balloon-pos="up">Product</th>
        <th aria-label="Product's buy price" data-balloon-pos="up">
          Buy Price
        </th>
        <th aria-label="Product's sell price" data-balloon-pos="up">
          Sell Price
        </th>
        <th aria-label="Product's buy volume" data-balloon-pos="up">
          Buy Volume
        </th>
        <th aria-label="Product's sell volume" data-balloon-pos="up">
          Sell Volume
        </th>
        <th>
          Margin
        </th>
      </tr>
    </thead>
    <tbody>
      {% for product in products %}
      <tr>
        <td>{{ product.id|replace("_", ' ')|lower()|title() }}</td>
        {% for buy in product.buy_price %}
        <td>{{ buy.pricePerUnit }}</td>
        {% for sell in product.sell_price %}
        <td>{{ sell.pricePerUnit }}</td>

        <td>{{ product.buy_volume| numberFormat }}</td>
        <td>{{ product.sell_volume| numberFormat }}</td>
        {% set margin = buy.pricePerUnit - sell.pricePerUnit%} {% set marginPer
        = margin/buy.pricePerUnit * 100%}
        <td
          aria-label="{{ marginPer|round(1, 'floor') }} % "
          data-balloon-pos="right"
        >
          {{ margin|round(1, 'floor')}}
        </td>
        {% endfor %}{% endfor %}
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

如果您需要 API 来测试它,我可以提供一个链接:)

标签: pythonflask

解决方案


您有 3 个选项:

我认为在您的情况下最好的选择是 SSE,因为服务器知道价格已更改,因此可以将其推送给客户。


推荐阅读