You can use HTTP request handlers to handle HTTP requests more easily. When calling a function, you Function Compute use the execution method you provide to handle the HTTP request. This topic describes the structure and features of the Python HTTP request handler.

Usage notes

Before using the HTTP request handler, make sure to configure an HTTP trigger for the HTTP function. For more information, see Configure an HTTP trigger.

HTTP Handler Signature

The signature of the Python HTTP Handler follows the WSGI (Python Web Server Gateway Interface) specification.

A simple HTTP Handler signature is defined as follows.

def handler(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [b'<h1>Hello, world!</h1>']

An example of an HTTP Handler signature is parsed as follows:

  • handler: an HTTP request processing function that meets WSGI standards. You can specify the following two parameters.
    • environ: stores information about all HTTP requests.
    • start_response: the function that sends an HTTP response.
  • start_response('200 OK', [('Content-Type', 'text/html')]): function response. Contains two parameters: the first parameter is an HTTP status code; the second parameter is an HTTP Headers that consists of a set of Python list objects. Each header is a Python tuple object that contains two Python str objects.
  • return [b'<h1>Hello, world!</h1>']: the returned information. This return value is returned to the client as the body of the HTTP response.

Example: Implementing a Flask Application

Sample code

After implementing the HTTP Handler that conforms to the WSGI protocol, applications based on popular Web frameworks such as Flask and Django can be migrated to Function Compute very quickly. The following code shows how to run hello world applications of the Flask framework in the Function Compute Python Runtime.

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Web App with Python Flask!'

def handler(environ, start_response):
    return app(environ, start_response)
The sample code is explained as follows:
  • Part 1: The code of the Flask application. From from flask import Flask to return 'Web App with Python Flask! 'End.
  • Part 2: handler functions. You only need to implement handler functions as return app(environ, start_response) to run Web framework applications such as Flask or Django in the Function Compute Python Runtime.

Prerequisites

Create a Service

Procedure

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where your Kubernetes cluster is deployed.
  4. On the Services page, click the target service.

  5. Create an HTTP function whose runtime environment is Python 3. For more information, see Create a function.
  6. On the Function Details page, click the Function Code tab, enter the preceding sample code in the code editor, and then pip install flask -t . it in the Terminal code input box. Install the Flask library to the current directory and click Save and Deploy.
  7. Click Test Function.
    After the function is successfully executed, view the returned result. You can see that the returned result is Web App with Python Flask!.

Request structure (environ)

Used to store information about HTTP requests. Its structure is a Python dictionary structure. The following table describes the common fields. For more information about the request structure, see environ.

Field Type Description
REQUEST_METHOD String HTTP request methods, such as GET and POST.
HTTP_Variables String The headers of the HTTP request.
CONTENT_TYPE String The type of the HTTP request body.
CONTENT_LENGTH String The length of the HTTP request body.
wsgi.input BytesIO The body of the HTTP request.
fc.request_uri String The URL of the client request, which is defined by the Function Compute.
fc.context FCContext Context, defined by Function Compute.
Note The parameter HTTP_Variables in the request structure (environ) is an HTTP request header that processes the key in the request header according to the WSGI specification. The processing method is key="HTTP_"+k.upper().replace("-","_"). For example, if a request header is a 'x-Custom-key':'value', it will appear as a environ['HTTP_X_CUSTOM_KEY']='value' in the request structure (environ).

The following sample code shows how to obtain the HTTP Handler request structure.

# Method 1: User provide the function. FC call the function to process request and send back response.

HELLO_WORLD = b"Hello world!\n"

def handler(environ, start_response):
    context = environ['fc.context']
    request_uri = environ['fc.request_uri']
    for k, v in environ.items():
        if k.startswith("HTTP_"):
            # process custom request headers
            pass

    # get request_body
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0
    request_body = environ['wsgi.input'].read(request_body_size)

    # get request_method
    request_method = environ['REQUEST_METHOD']

    # get path info
    path_info = environ['PATH_INFO']

    # get server_protocol
    server_protocol = environ['SERVER_PROTOCOL']

    # get content_type
    try:
        content_type = environ['CONTENT_TYPE']
    except (KeyError):
        content_type = " "

    # get query_string
    try:
        query_string = environ['QUERY_STRING']
    except (KeyError):
        query_string = " "

    print ('request_body: {}'.format(request_body))
    print ('method: {}\n path: {}\n  query_string: {}\n server_protocol: {}\n'.format(request_method, path_info,  query_string, server_protocol))
    # do something here

    status = '200 OK'
    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)
    # return value must be iterable
    return [HELLO_WORLD]

The returned data.

The HTTP Handler response structure contains the response status, response header, and response body. You need to call the start_response() and return the response status status and the contents headers by the response header to the server before the response body can be returned. The response body is required to be an iterative object.

start_response is a Callable structure. The following example shows the structure. For more information about start_response, see the-start-response-callable.

# Provided by FC runtime.
# status: a string like '200 OK' or '403 FORBIDDEN'
# return: must be a write(body_data) callable
def start_response(status, response_headers, exc_info=None):
...

Parameter description:

Field Type Description
status String The HTTP status code.
response_headers List The HTTP response header.
exc_info List Used to return the current exception information as a tuple. The Function Compute is currently not in use.