阿里雲函式計算使用體驗
環境安裝
-
在此案例中,使用阿里雲伺服器。(Linux)
-
使用官方安裝指令碼自動安裝
curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun 複製程式碼
- 安裝fun
npm install @alicloud/fun -g 複製程式碼
- 配置fun,按提示輸入資訊
fun config 複製程式碼
基礎:建立Helloworld檔案
1\. 建立一個資料夾,如image_crawler 2\. 建立一個檔案template.yml,內容 ROSTemplateFormatVersion: '2015-09-01' Transform: 'Aliyun::Serverless-2018-04-03' Resources: localdemo: Type: 'Aliyun::Serverless::Service' Properties: Description: 'local invoke demo' image-crawler: Type: 'Aliyun::Serverless::Function' Properties: Handler: index.handler CodeUri: code/ Description: 'Hello world with python2.7!' Runtime: python2.7 3\. 建立一個code資料夾,在資料夾中編寫helloworld程式碼 def handler(event, context): return 'hello world!' 4\. 執行函式 fun local invoke image-crawler 複製程式碼
進階:設定oss轉存任務,如一個image_crawler
- 獲取網頁原始碼,按上述語句執行image-crawler,可看到變化。
import logging import json import urllib logger = logging.getLogger() def handler(event, context): logger.info("event: " + event) evt = json.loads(event) url = evt['url'] html = get_html(url) logger.info("html content length: " + str(len(html))) return 'Done!' def get_html(url): page = urllib.urlopen(url) html = page.read() return html 複製程式碼
- 執行以下語句可看到變化
echo '{"url":"http://huaban.com/search/?q=%e5%a3%81%e7%ba%b8"}' | fun local invoke image-crawler 複製程式碼
- 新增函式,從原始碼中抽取圖片路徑
def get_img(html): reg = r'https:\/\/[^\s,"]*\.jpg' imgre = re.compile(reg) return re.findall(imgre, html) 複製程式碼
- 調整替換原先的handler函式,使之從“獲取網頁原始碼”功能轉變為“獲取圖片路徑功能”。
def handler(event, context): logger.info("event: " + event) evt = json.loads(event) url = evt['url'] html = get_html(url) img_list = get_img(html) logger.info(img_list) return 'Done!' 複製程式碼
- 將圖片上傳到OSS中,在 template 中配置環境變數(需提前建立好 oss bucket):
EnvironmentVariables: OSSEndpoint: oss-cn-hangzhou.aliyuncs.com BucketName: fun-local-test 複製程式碼
- 然後就可以直接在函式中獲取到這兩個環境變量了:
endpoint = os.environ['OSSEndpoint'] bucket_name = os.environ['BucketName'] 複製程式碼
- 設定OSS的STS許可權控制,參考如下程式碼
creds = context.credentials if (local): auth = oss2.Auth(creds.access_key_id, creds.access_key_secret) else: auth = oss2.StsAuth(creds.access_key_id, creds.access_key_secret, creds.security_token) bucket = oss2.Bucket(auth, endpoint, bucket_name) 複製程式碼
- 遍歷所有圖片檔案,並且轉存到OSS中
count = 0 for item in img_list: count += 1 logging.info(item) # Get each picture pic = urllib.urlopen(item) # Store all the pictures in oss bucket, keyed by timestamp in microsecond unit bucket.put_object(str(datetime.datetime.now().microsecond) + '.png', pic) 複製程式碼
- 完整的程式碼
import logging,datetime import json,re,oss2 import requests,urllib,os logger = logging.getLogger() endpoint = os.environ['OSSEndpoint'] bucket_name = os.environ['BucketName'] local = 1 def handler(event, context): logger.info("event: " + event) evt = json.loads(event) url = evt['url'] print(url) creds = context.credentials if (local): auth = oss2.Auth(creds.access_key_id,creds.access_key_secret) else: auth = oss2.StsAuth(creds.access_key_id,creds.access_key_secret,creds.security_token) bucket = oss2.Bucket(auth, endpoint, bucket_name) html = get_html(url) img_list = get_img(html) logger.info(img_list) iii(img_list,bucket) return 'Done!' def iii(img_list,bucket): count = 0 for item in img_list: count += 1 logging.info(item) pic = urllib.urlopen(item) if pic != None: bucket.put_object(str(datetime.datetime.now().microsecond) + '.jpg', pic) def get_img(html): reg = r'http:\/\/[^,"]*\.jpg' imgre =re.compile(reg) return re.findall(imgre,html) def get_html(url): page = requests.get(url) html = page.content return html 複製程式碼
-
此時執行如下命令可看到成功效果。
echo '{"url":"http://huaban.com/search/?q=%e5%a3%81%e7%ba%b8"}' | fun local invoke image-crawler 複製程式碼
部署
- 新增OSS許可權到yaml中,此次是添加了policies:AliyunOSSFullAccess。注意localdemo這個函式計算專案及image-crawler這個函式,fun-local-test這個OSS專案bucket需要事先在阿里雲官網後臺配置過。
ROSTemplateFormatVersion: '2015-09-01' Transform: 'Aliyun::Serverless-2018-04-03' Resources: localdemo: Type: 'Aliyun::Serverless::Service' Properties: Description: 'local invoke demo' Policies: AliyunOSSFullAccess image-crawler: Type: 'Aliyun::Serverless::Function' Properties: Handler: index.handler CodeUri: code/ Description: 'Hello world with python2.7!' Runtime: python2.7 EnvironmentVariables: OSSEndpoint: oss-cn-hangzhou.aliyuncs.com BucketName: fun-local-test 複製程式碼
- 使用fun deploy 即看到執行成功。
- 登入臺阿里雲函式計算後臺,可以看到這個專案程式碼,可以線上修改配置。
思考:函式計算適合做什麼用途?
-
定時任務,如爬蟲類。(圖片轉存、文字轉存等)
-
pipeline類別,如接受A資訊,轉存到B資訊及格式。根據if,else等來分類的任務。
-
微信,釘釘等公眾號的後端(Flask),免去搭建伺服器。
-
可以一個函式就解決的任務與專案,特別簡單的專案。
-
阿里雲官方函式計算後臺提供Flask-web型別的函式計算模組,可以快速搭建外網api可訪問的介面與頁面。