如何将 webhook 事件添加到 Flask 服务器?

Cod*_*ine 5 python events server-side webhooks flask

我一直在到处寻找有关如何创建和实现在后端 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()
Run Code Online (Sandbox Code Playgroud)

我写什么来监听服务器事件?

小智 2

您可以使用before_request像这样调用的 Flask 功能

\n
from flask import Flask, jsonify, current_app, request\n\napp = Flask(__name__)\n\n\n@app.before_request\ndef hook_request():\n    Flask.custom_variable = {\n        "message": "hello world",\n        "header": request.args.get("param", None)\n    }\n\n\n@app.route(\'/\')\ndef home():\n    variable = current_app.custom_variable\n    return jsonify({\n        "variable": variable,\n    })\n\n\nif __name__ == \'__main__\':\n    app.run()\n
Run Code Online (Sandbox Code Playgroud)\n

并像这样测试它

\n
\xe2\x86\x92 curl http://localhost:5000/  \n{"message":"hello world"}\n\n\xe2\x86\x92 curl http://localhost:5000\\?param\\=example\n{"variable":{"header":"example","message":"hello world"}}\n
Run Code Online (Sandbox Code Playgroud)\n