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 links to some commonly asked questions.
Background information
In a custom runtime, Function Compute forwards common headers, a request body, the POST method, the /invoke path, and the /initialize path to your HTTP server. Common headers can be used to build a parameter that is similar to the context
input parameter in an official runtime. You can also build an input parameter that is similar to the event
parameter 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 POST /invoke
.
Path | Request | Expected response |
POST |
Important
| Response body: the returned value of the function handler. |
Sample code
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)
In the preceding sample code:
@app.route("/invoke", methods = ["POST"])
: adds thehello_world
function that uses the/invoke
path 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 response body.
Event handlers cannot return status codes or response headers. For example, if you use the Flask web framework, the status code and response headers to be returned by return "Hello, World!", 400, [('Author', 'Aliyun-FC')]
do not take effect.
Examples for 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.