我一直在到处寻找有关如何创建和实现在后端 API 中监听事件的 webhook 的教程。例如,如果我有一个用 python flask 编写的服务器,我将如何监听服务器端事件(例如:用户创建了 100 条记录),然后执行更多的后端代码或请求外部数据?
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return {"status": 200}
#Some webhook code listening for events in the server
if __name__ == '__main__':
app.run()
我写什么来监听服务器事件?
最佳答案
您可以使用名为 before_request
的 flask 功能它像这样
from flask import Flask, jsonify, current_app, request
app = Flask(__name__)
@app.before_request
def hook_request():
Flask.custom_variable = {
"message": "hello world",
"header": request.args.get("param", None)
}
@app.route('/')
def home():
variable = current_app.custom_variable
return jsonify({
"variable": variable,
})
if __name__ == '__main__':
app.run()
并测试它like this
→ curl http://localhost:5000/
{"message":"hello world"}
→ curl http://localhost:5000\?param\=example
{"variable":{"header":"example","message":"hello world"}}
关于python - 如何将 webhook 事件添加到 Flask 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57779365/