【发布时间】: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 并启动一个任务。
资源探索失败:
【问题讨论】:
-
这听起来最好由您的前端使用一些 JavaScript 来更新值,而不是重新加载整个页面。
-
如果我在 /index 路由中调用 api,JS 将无济于事
-
也许我不明白这个问题,因为我看不出在
index中调用 API 会如何阻止使用 JavaScript 更新值。 -
index中的值只有在加载时才会更新,我不知道如何在不加载index的情况下获取值。也不是 JS 专家
标签: javascript python html flask