如何在不刷新 Flask 项目页面的情况下更新值?

8 python flask

我有一个网站,显示视频游戏中物品的价格。

目前,我有一个“自动刷新”脚本,每 5 秒刷新一次页面,但这有点烦人,因为每次您搜索产品时,它都会因为页面刷新而删除您的搜索。

我想更新表中的数字而不刷新用户的页面。我在 javascript 中读到了一些关于“更新 DOM”的内容,但没有明白。

这是我的网站的链接: http: //xeltool.com/

这是我的 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)
Run Code Online (Sandbox Code Playgroud)

这是我的 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>
Run Code Online (Sandbox Code Playgroud)

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

bal*_*man 12

您有 3 个选择:

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