【问题标题】:Carry out realtime updates over Flask cache or POST request changes通过 Flask 缓存或 POST 请求更改执行实时更新
【发布时间】:2021-11-11 20:52:27
【问题描述】:

webhook 的概念非常简单,但我在这里是为了获得一些关于如何处理 POST 请求中的实时更改的指导。 考虑 FLASK 中的 webhook 程序:

@app.route('/webhook', methods = ['POST'])
def webhook():
    data = json.loads(request.data)
    
    return data

这样的程序很容易返回一个 json POST 请求。结果将如下所示:

{
"passphrase": "SkZSV1YwZz0=",
"timenow": "2021-09-15T21:18:00Z",
"item": "apple",
"quantity": "50",
"account": "9999"
}

现在我已经成功读取了 webhook 数据。下一步是对数据做一些事情。 假设我想在我的数据库'df' 中搜索item: apple 并返回价格。

def get_item_price(df, item_name):
    # Returns price by filtering df.
    df = df[df['name'] == item_name]
    df.reset_index(inplace = True)
    price = df['price']
    return price

所以,现在可以使用price_of_item = get_item_price(df, item_name)。但是由于 webhook 是一个 POST 请求,我使用缓存来访问来自其他路由的值。

cache.set("price_data", price_of_item )

我可以通过从另一个路由调用缓存来获取苹果的价格。说:

@app.route("/index")
def index():
    price_data_recieved= cache.get("price_data")

    # do some stuff based on price_data_recieved, and call a api
    
    return index_template.format(message = price_of_item)

index_template = """
    <div> the price of apple is: {price_data_recieved}{some_other_stuff} </div>
    """

但这不是实时的,我每次都需要重新加载浏览器。我可以对此进行更改,以便新的 POST 请求也更改我的 index 路由输出。我假设它就像对/index 的 ping 并启动一个任务。

资源探索失败:

  1. Make a POST request while redirecting in flask
  2. Display data streamed from a Flask view as it updates
  3. Update and render a value from Flask periodically
  4. Execute a function after Flask returns response

【问题讨论】:

  • 这听起来最好由您的前端使用一些 JavaScript 来更新值,而不是重新加载整个页面。
  • 如果我在 /index 路由中调用 api,JS 将无济于事
  • 也许我不明白这个问题,因为我看不出在 index 中调用 API 会如何阻止使用 JavaScript 更新值。
  • index 中的值只有在加载时才会更新,我不知道如何在不加载 index 的情况下获取值。也不是 JS 专家

标签: javascript python html flask


【解决方案1】:

我将使用 While 循环检查缓存值是否已从以前存储的一次更改,直到有更好的方法可用。

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 2023-03-16
    • 1970-01-01
    • 2022-11-10
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 2019-04-28
    • 2021-04-03
    相关资源
    最近更新 更多