编程技术

【20181205】阿里云函数计算使用体验

2018-12-06  本文已影响10人  小谷先生
image

环境安装

curl -fsSL https://get.docker.com | bash -s docker --mirror Aliyun

npm install @alicloud/fun -g

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

image

进阶:设置oss转存任务,如一个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)

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!'

EnvironmentVariables:
    OSSEndpoint: oss-cn-hangzhou.aliyuncs.com
    BucketName: fun-local-test

endpoint = os.environ['OSSEndpoint']
bucket_name = os.environ['BucketName']

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)

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

部署

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

image

思考:函数计算适合做什么用途?

参考资料

上一篇 下一篇

猜你喜欢

热点阅读