Alibaba Cloud DevOps Cookbook Part 3 — Function Compute with Python 3.0

Function Compute Interfaces

Function Definition when Called by an HTTP Trigger

def my_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
# do something here status = '200 OK'
response_headers = [('Content-type', 'text/plain')]
start_response(status, response_headers)
return ["Hello World"]

Function Definition when Called by the Invoke API or by API Gateway

def my_handler(event, context):
body = 'hello world'
res = {
'isBase64Encoded': False,
'statusCode': 200,
'headers': {
'content-type' : 'text/plain'
},
'body': body
}
return json.dumps(res)

Example Program That Will Return Parameter “environ” in HTML

############################################################
# Version 1.01
# Date Created: 2018-05-25
# Last Update: 2018-05-29
# https://www.neoprime.io
# Copyright (c) 2018, NeoPrime, LLC
############################################################
""" Alibaba Cloud Function Compute Example """
""" This program will return the environment back to the caller as an HTML table """
""" This is useful to learn about the running environment in Function Compute """
""" This code is designed to be called thru HTTP URL via an HTTP Trigger """
def handler(environ, start_response):
body = '<!DOCTYPE html>\n<html lang="en"><head>\n'
body = body + '<style>\n'
body = body + 'table, th, td {border: 1px solid black;}\n'
body = body + 'table {border-collapse: collapse;}\n'
body = body + 'th, td {border: 1px solid #ddd; padding 8px;}\n'
body = body + 'th {padding-top: 12px; padding-bottom: 12px;\n'
body = body + 'text-align: left; background-color: #4CAF50;color: white;}\n'
body = body + 'tr:nth-child(even){background-color: #f2f2f2;}\n'
body = body + 'tr:hover {background-color: #ddd;}\n'
body = body + '</style>\n'
body = body + '</head>\n<body><table width="%100%">\n'
body = body + "<thead>\n<tr><th>Name</th><th>Type</th><th>Value</th></tr>\n</thead>\n"
body = body + "<tbody>\n"
for k, v in environ.items():
body = body + "<tr>"
body = body + "<td>" + k + "</td>"
body = body + "<td>" + type(v).__name__ + "</td>"
if isinstance(v, bool):
body = body + "<td>" + str(v) + "</td>"
if isinstance(v, str):
body = body + "<td>" + v + "</td>"
if isinstance(v, tuple):
body = body + "<td>" + str(v) + "</td>"
if isinstance(v, type):
body = body + "<td>" + str(v) + "</td>"
body = body + "</tr>\n"
body = body + "</tbody>\n</table>\n</body></html>"
status = '200 OK'
response_headers = [('Content-type', 'text/html')]
start_response(status, response_headers)
return [bytes(body, "utf-8")]

Example Program That Will Return Parameter “context” in HTML

############################################################
# Version 1.01
# Date Created: 2018-05-25
# Last Update: 2018-05-29
# https://www.neoprime.io
# Copyright (c) 2018, NeoPrime, LLC
############################################################
""" Alibaba Cloud Function Compute Example """
""" This program will return the environment back to the caller as an HTML table """
""" This is useful to learn about the running environment in Function Compute """
""" This code is designed to be called thru API Gateway using an HTTP URL """
import json# Add a row to the HTML table
def add_row(body, name, value):
""" body - the current HTML body string that we append to """
""" name - the name of the item. Added to the first column """
""" value - the value to add. The type is added to the second column, value to the third """
""" returns body """
# begin a new table row
body = body + '<tr>\n'
body = body + '<td>' + name + '</td>\n'
body = body + '<td>' + type(value).__name__ + '</td>\n'
if isinstance(value, str):
# Keep the string length less than 85 characters
v = (value[:85] + ' ...') if len(value) > 85 else value
body = body + '<td>' + v + '</td>\n'
else:
body = body + '<td>' + str(value) + '</td>\n'
return body + '</tr>\n'# Add a "dict" item to the table by parsing thru each item in the dictionary
def add_dict(body, name, item):
""" body - the current HTML body string that we append to """
""" name - the name of the item. """
""" item - The item to process """
for k in item:
if isinstance(item[k], dict):
body = add_dict(body, name + "." + k, item[k])
else:
body = add_row(body, name + "." + k, item[k])
return body
def add_event(body, event):
j = json.loads(event.decode("utf-8"))
return add_dict(body, "event", j)
def add_context(body, context):
body = add_row(body, 'context.request_id', context.request_id)
body = add_row(body, 'context.region', context.region)
body = add_row(body, 'context.account_id', context.account_id)
body = add_row(body, 'context.function.handler', context.function.handler)
body = add_row(body, 'context.function.memory', context.function.memory)
body = add_row(body, 'context.function.name', context.function.name)
body = add_row(body, 'context.function.timeout', context.function.timeout)
body = add_row(body, 'context.credentials.accessKeyId', context.credentials.accessKeyId)
body = add_row(body, 'context.credentials.accessKeySecret', context.credentials.accessKeySecret)
body = add_row(body, 'context.credentials.access_key_id', context.credentials.access_key_id)
body = add_row(body, 'context.credentials.access_key_secret', context.credentials.access_key_secret)
body = add_row(body, 'context.credentials.securityToken', context.credentials.securityToken)
body = add_row(body, 'context.credentials.security_token', context.credentials.security_token)
body = add_row(body, 'context.service.log_project', context.service.log_project)
body = add_row(body, 'context.service.log_store', context.service.log_store)
return bodydef build_html(body, event, context):
body = '<!DOCTYPE html>\n<html lang="en"><head>\n'
body = body + '<style>\n'
body = body + 'table, th, td {border: 1px solid black;}\n'
body = body + 'table {border-collapse: collapse;}\n'
body = body + 'th, td {border: 1px solid #ddd; padding 8px;}\n'
body = body + 'th {padding-top: 12px; padding-bottom: 12px;\n'
body = body + 'text-align: left; background-color: #4CAF50;color: white;}\n'
body = body + 'tr:nth-child(even){background-color: #f2f2f2;}\n'
body = body + 'tr:hover {background-color: #ddd;}\n'
body = body + '</style>\n'
body = body + '</head>\n<body><table width="100%">\n'
body = body + '<thead>\n<tr><th>Name</th><th width="5%">Type</th><th>Value</th></tr>\n</thead>\n'
body = body + '<tbody>\n'
body = add_event(body, event)
body = add_context(body, context)
body = body + '</tbody>\n'
body = body + '</table>\n</body></html>'
return bodydef handler(event, context):
body = ""
body = build_html(body, event, context)
res = {
'isBase64Encoded': False,
'statusCode': 200,
'headers': {
'content-type' : 'text/html'
},
'body': body
}
return json.dumps(res)

Function Compute Access Keys

Alibaba Documentation

--

--

--

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Introduction to Compiler Construction: Part 1

SessionStack’s Year in Review: What We Shipped, Where We Hung Out, and Who We Talked to

Tableau | 5 Calculated Field Hacks

JIRA Team Metrics: Tracking Velocity in Your JIRA Dashboard

JIRA dashboard reporting - Story Point JQL Recipe Creation.png

Product Management for Small Businesses: Development

Amazing Classes and Objects

Sample Application DDD Reactive Microservices with CQRS & Event Sourcing

Woocommerce Telegram Robot

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alibaba Cloud

Alibaba Cloud

Follow me to keep abreast with the latest technology news, industry insights, and developer trends. Alibaba Cloud website:https://www.alibabacloud.com

More from Medium

AWS LANDING ZONE vs. CONTROL TOWER

AWS CDK-CLI Commands

How to make AssumeRolewithSAML calls with AWS CLI

5GC deployment on AWS Cloud

The trend of deploying core network on cloud