This topic describes the structure of event handlers in a custom runtime. This topic also provides examples on how to use event handlers in a custom runtime and answers to commonly asked questions.
Background informationIn a custom runtime, Function Compute forwards the common headers, the request body, the POST method, the /invoke path, and the /initialize path to your HTTP server. You can build an input parameter that is similar to the
contextparameter in an official runtime based on the information in common headers. You can also build an input parameter that is similar to the
eventparameter in an official runtime based on the request body of the invoked function.
Signatures for event handlers
If a function uses an event handler, the HTTP server needs to implement the logic that corresponds to the
/invoke path and the
POST method. Function Compute automatically routes requests to
|Response body: the returned value of the function handler.|
In the following sample code, the Flask web framework that is written in Python 3.10 runtime is used.
from flask import Flask from flask import request import sys REQUEST_ID_HEADER = 'x-fc-request-id' app = Flask(__name__) @app.route("/invoke", methods = ["POST"]) def hello_world(): rid = request.headers.get(REQUEST_ID_HEADER) print("FC Invoke Start RequestId: " + rid) data = request.stream.read() print(str(data)) print("FC Invoke End RequestId: " + rid) return "Hello, World!", 200, [()] if __name__ == '__main__': app.run(host='0.0.0.0',port=9000)
@app.route("/invoke", methods = ["POST"]): adds the
hello_worldfunction that uses the
/invokepath and the POST method by using the Flask web framework,
rid = request.headers.get(REQUEST_ID_HEADER): obtains the request ID in the request header.
data = request.stream.read(): obtains the request body.
return "Hello, World!": sends the request body.
return "Hello, World!", 400, [('Author', 'Aliyun-FC')]do not take effect.
Examples of other programming languages
You can use Serverless Devs to migrate your applications to Function Compute with a few clicks. The following example shows how to use Serverless Devs to deploy and invoke a function in an efficient manner. You can modify the sample code based on your business requirements.
- Must the listening port of a custom runtime be the same as that of the HTTP server of the custom runtime?
- What do I do if the FunctionNotStarted error occurs when I invoke a third-party service in a service started in a custom runtime?
- What do I do if a function exits unexpectedly and the "Process exited unexpectedly before completing request" message is reported?
- What do I do if a 404 error occurs when I use a browser or the cURL tool to access a function?