Event handlers

更新时间:
复制 MD 格式

In a custom runtime, Function Compute forwards event invocations to your HTTP server at POST /invoke with common headers. Your server processes the event and returns the result as the response body.

image

Quick start

Minimal Flask event handler (Python 3.10):

from flask import Flask, request

REQUEST_ID_HEADER = 'x-fc-request-id'

app = Flask(__name__)

@app.route("/invoke", methods=["POST"])
def handler():
    # Extract the request ID from common headers
    rid = request.headers.get(REQUEST_ID_HEADER)
    print("FC Invoke Start RequestId: " + rid)

    # Read the event payload
    data = request.stream.read()
    print(str(data))

    print("FC Invoke End RequestId: " + rid)
    # Return the response body
    return "Hello, World!"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9000)

Key points:

  • @app.route("/invoke", methods=["POST"]) registers the POST /invoke handler.

  • request.headers.get(REQUEST_ID_HEADER) extracts the request ID from common headers.

  • request.stream.read() reads the event payload.

  • return "Hello, World!" returns the response body to the caller.

How it works

Function Compute routes each invocation to your HTTP server as follows:

  1. Function Compute sends the event payload to POST /invoke with common headers (request ID, function name, credentials, etc.).

  2. Your HTTP server processes the event and runs your business logic.

  3. Your server returns the result as the response body, which Function Compute delivers to the caller.

Function Compute also sends a POST /initialize request when a new instance starts. Implement this path for one-time setup such as loading models or establishing database connections.

Request and response format

Request

Component Details
Method and path POST /invoke
Headers Common headers (x-fc-request-id, function metadata, temporary credentials).
Body The event payload passed to the InvokeFunction API.
Content-Type application/octet-stream

Response

Return the function result as the response body.

Important

Only the response body is returned to the caller. Status codes and headers are ignored. For example, return "Hello, World!", 400, [('Author', 'Aliyun-FC')] delivers only the body — the 400 status and Author header are discarded.

More language examples

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.

FAQ