This topic describes the handler and deployment framework of Python HTTP functions.
Function handler
In Python runtime environments, the signature of a function follows the Python Web Server Gateway Interface (WSGI) specification. You can process requests based on the WSGI specification.
Handler
Python HTTP functions provide two types of handlers:
- Handler 1
# 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]
- Handler 2
# Method 2: User provide the callable class object. FC call the object to process request and send back response. HELLO_WORLD = b"Hello world! \n" class AppClass: """Produce the same output, but using a class """ def __init__(self, environ, start_response): self.environ = environ self.start = start_response def __iter__(self): status = '200 OK' response_headers = [('Content-type', 'text/plain')] self.start(status, response_headers) yield HELLO_WORLD def handler(environ, start_response): return AppClass(environ, start_response)
Paramters
- environ: indicates the Python dictionary that stores all client-related information. For
more information, see environ Variables. In addition to the variables included in the dictionary, Function Compute provides
two user-defined keys: fc.context and fc.request_uri.
- fc.context has the same meaning as the context parameter of Python event functions.
- fc.request_uri indicates the request URL of the string type.
Note The
HTTP_Variables
field in the environ parameter contains the request header. For example, if the request header is'x-Custom-key':'value'
, the environ parameter isenviron['HTTP_X_CUSTOM_KEY']='value'
. Based on WSGI, the key in the request header is processed askey = "HTTP_" + k.upper().replace("-","_")
.
- start_response: indicates a callable provided in runtime environments of Function Compute. For more
information, see The start_response() Callable.
The start_response parameter has two required position parameters and one optional parameter. In the following sample code, the three parameters are named status, response_headers, and exc_info.
# 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): ...
- status: indicates the HTTP response status, which is a string.
- response_headers: indicates the HTTP response headers. It is a list that contains a tuple in the (header_name, header_value) format.
- exc_info: indicates the information that the server needs to return to the client. This parameter is optional.
After the application object completes executing the business logic based on the environ parameter, the application object must return the result to the server. An HTTP response
must contain the status, headers, and body parameters. Therefore, before the application
returns the value of body, you must call the start_response()
function to return the value of status and headers to the server. In this way, the server knows that the application starts to return
the value of body.
Get the request body
You can use WSGI to get the raw body.
The following sample code shows how to get the request body:
# 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)
References
The preceding example of handler function 2 shows that you can run projects that are built by using WSGI-based web frameworks such as Flask and Django in Python runtime environments of Function Compute. For more information, see Deploy Python projects based on WSGI-based web frameworks to Function Compute.