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 informationIn 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.
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 /invoke
Request body: the function input, which is the payload that you specify when you call the InvokeFunction operation.
Request header: common request headers. For more information, see Common request headers in Function Compute.
Content-Type
must be application/octet-stream
.
Response body: the returned value of the function handler.
Sample codeIn 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 the hello_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.
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.
FAQRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4