全部文档
当前文档

暂无内容

如果没有找到您期望的内容,请尝试其他搜索词

文档中心

请求处理程序开发方法

最近更新时间:2022-12-13 10:49:28

本文介绍在云函数KCF中使用Python语言开发请求处理程序的相关概念和方法。

请求处理程序分为事件请求处理程序(Event Handler)和HTTP请求处理程序(HTTP Handler);其中事件请求由各种事件源触发生成,HTTP请求则由HTTP触发器触发生成。
请求处理程序的具体配置示例如下:

事件请求处理程序(Event Handler)

介绍Python事件请求处理程序的结构和特点。

使用示例

在Python语言的代码中,使用pip引入Flask Web框架时,同时引入cloudevents官方的SDK库 :

pip3 install flask -t .
pip3 install cloudevents -t .
flask框架 + cloudevents 代码示例
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的示例解析如下:

  • handler函数。与函数计算控制台配置的触发器请求路径相对应。例如,为KCF函数配置的handler为event-invoke,那么函数计算会去加载main.py中定义的handler函数,并从handler函数开始执行。
  • from_http: 将事件请求内容转换成cloudevents结构体。

cloudevents详细介绍:

HTTP请求处理程序(HTTP Handler)

介绍Python HTTP请求处理程序的结构和特点。

在Python语言的代码中,使用pip引入Flask web框架,J将Flask库安装到当前目录下 :

pip3 install flask -t .

flask框架代码示例

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的示例解析如下:

  • handler:方法名称。与函数计算控制台配置的请求路径(函数入口)相对应。例如,为FC函数配置的handler为/http-invoke,那么函数计算会去加载main.py中定义的handler函数,并从handler函数开始执行。
  • return “receive patch msg”, 200: 返回信息。此返回值将作为HTTP响应的Body返回给客户端。
文档导读
纯净模式常规模式

纯净模式

点击可全屏预览文档内容
文档反馈