最近更新时间:2022-12-13 10:49:28
本文介绍在云函数KCF中使用Python语言开发请求处理程序的相关概念和方法。
请求处理程序分为事件请求处理程序(Event Handler)和HTTP请求处理程序(HTTP Handler);其中事件请求由各种事件源触发生成,HTTP请求则由HTTP触发器触发生成。
请求处理程序的具体配置示例如下:
介绍Python事件请求处理程序的结构和特点。
在Python语言的代码中,使用pip引入Flask Web框架时,同时引入cloudevents官方的SDK库 :
pip3 install flask -t .
pip3 install cloudevents -t .
import json
import os
# import sys
# import flask dependency
# - name: PYTHONPATH
# value: /opt/python
# sys.path.append('/opt/python')
from cloudevents.http import from_http
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/event-invoke", methods=["POST"])
def event_invoke():
# create a CloudEvent
event = from_http(request.headers, request.get_data())
# you can access cloudevent fields as seen below
print(
f"Found {event['id']} from {event['source']} with type "
f"{event['type']} and specversion {event['specversion']}"
)
return "receive event message", 200
@app.route("/health")
def health_check():
return "<p>Hello, World Flask!</p>", 200
if __name__ == "__main__":
# app.run(port=8080)
app.run(host='0.0.0.0', port=8080, debug=True)
requirements.txt
cloudevents==1.6.1
Flask==2.1.2
Event Handler的示例解析如下:
cloudevents详细介绍:
介绍Python HTTP请求处理程序的结构和特点。
在Python语言的代码中,使用pip引入Flask web框架,J将Flask库安装到当前目录下 :
pip3 install flask -t .
import json
import os
# import flask dependency with layer
# sys.path.append('/opt/python')
from cloudevents.http import from_http
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route("/http-invoke", methods=["GET"])
def get_handler():
print("receive http get msg")
print('request.args = ', request.args)
return "receive get msg", 200
@app.route("/http-invoke", methods=["POST"])
def post_handler():
print("receive http post msg")
print('request.args = ', request.args)
data = request.stream.read()
if data is None or data == b"":
# Empty string will cause data to be marshalled into None
return "body data is none", 400
json_data = json.loads(data)
print('request.body = ', json_data['id'])
# print('id =', data['id'])
# return "receive post msg", 200
return jsonify({'id': "a123"}), 200
@app.route("/http-invoke", methods=["PUT"])
def put_handler():
print("receive http put msg")
print('request.args = ', request.args)
return "receive put msg", 200
@app.route("/http-invoke", methods=["delete"])
def delete_handler():
print("receive http delete msg")
print('request.args = ', request.args)
return "receive delete msg", 200
@app.route("/http-invoke", methods=["PATCH"])
def patch_handler():
print("receive http patch msg")
print('request.args = ', request.args)
return "receive patch msg", 200
def print_env():
env_dist = os.environ # environ是在os.py中定义的一个dict environ = {}
for key in env_dist:
print(key + ' : ' + env_dist[key])
if __name__ == "__main__":
# app.run(port=8080)
app.run(host='0.0.0.0', port=8080, debug=True)
requirements.txt
Flask==2.1.2
HTTP Handler的示例解析如下:
纯净模式