閱讀228 返回首頁    go 阿裏雲 go 技術社區[雲棲]


阿裏雲函數計算支持 Python 運行環境

阿裏雲函數計算服務是一個事件驅動的全托管計算服務,自 4 月份發布以來,受到了很多開發者的關注。通過函數計算,開發者隻需要編寫函數代碼,就能夠快速地開發出彈性伸縮地 Serverless 應用。

今天函數計算北京區域(華北 2)正式上線,同時推出了對 Python 語言的支持,開發者可以使用 Python 來編寫函數。一個最簡單的函數代碼如下:

def my_handler(event, context):
    return 'hello world'
  1. 函數名
    • my_handler需要與創建函數時的"Handler"字段相對應:例如創建函數時指定的 Handler 為main.my_handler,那麼函數計算會去加載main.py中定義的my_handler函數
  2. event 參數
    • event 參數是用戶調用函數時傳入的數據,其類型是str
  3. context 參數
    • context 參數中包含一些函數的運行時信息(例如 request id/臨時 AK 等)。其類型是FCContext,具體結構和使用在下麵的使用 context介紹
  4. 返回值
    • 函數的返回值會作為調用函數的結果返回給用戶,它可以是任意類型:對於簡單類型會函數計算會把它轉換成 str 返回,對於複雜類型會把它轉換成 JSON 字符串返回

更詳細的介紹請參考Python 編程指南

結合API 網關,開發者可以方便地將自己的函數以 HTTP 的方式提供給別人使用。

下麵是一個簡單的圖片拚接和旋轉的例子

fc-python-demo

代碼如下:

import base64
import logging
import random

import oss2
from wand.image import Image

TEMPLATE = open('/code/index.html').read()

def my_handler(event, context):
    logger = logging.getLogger()
    logger.info('event: %s', event)

    creds = context.credentials
    auth = oss2.StsAuth(creds.accessKeyId, creds.accessKeySecret, creds.securityToken)
    bucket = oss2.Bucket(auth, 'oss-cn-shanghai-internal.aliyuncs.com', 'rockuw-sh-2')

    fc_obj = bucket.get_object('fc.png')
    py_obj = bucket.get_object('python.png')

    with Image(file=fc_obj) as fc_img:
        with Image(file=py_obj) as py_img:
            img = Image()
            img.blank(fc_img.width + py_img.width + 20, py_img.height)
            img.composite(image=fc_img, left=0, top=0)
            img.composite(image=py_img, left=fc_img.width+20, top=0)
            img.rotate(random.randint(0, 360))
            img_enc = base64.b64encode(img.make_blob(format='png'))

    resp = {
        'isBase64Encoded': False,
        'statusCode': 200,
        'body': TEMPLATE.replace('{fc-py}', img_enc)
    }

    return resp

歡迎各位 Python 大拿來玩!

參考:

https://www.v2ex.com/t/360304
https://www.v2ex.com/t/368118

最後更新:2017-07-07 15:32:30

  上一篇:go  IP花式玩法背後,海瀾之家營銷思路出現哪些變化?
  下一篇:go  天貓超市香港奇遇記:老幹媽飯掃光成港人最愛