openfass学习及使用

1.首先你得先安装docker Docker CE 17.05或者更高都可以,windows系统请安装Git bash

2.安装OpenFass
$ git clone htpps://github.com/openfaas/faas

3.在Docker守护程序上初始化Swarm
$ docker swarm init 

4.部署Fass和示例函数
$ cd faas 
$ ./deploy_stack.sh

5.安装CLI
Mac:
$ brew install faas-cli
Linux:
$ curl -sSL https://cli.openfass.com | sudo sh
如果您使用的是Windows,那么您运气不错,您可以在FaaS版本页面上找到Windows可执行文件。

6.编写您的功能:
$ mkdir -p ~/functions && \ 
  cd ~/functions

7.使用CLI构建一个新的python函数
$ faas-cli new --lang python hello-python

这会为您创建三个文件你可以使用ls查看:
hello-python/handler.py
hello-python/requirements.txt
hello-python.yml

8.编辑handler.py文件实现你的需求,比如:
def handle(req):
    print("Hello! You said:"+req)

9.查看yml文件,他会告诉你CLI要在OpenFass上构建和部署什么
$ vim hello-python.yml
$ gateway:如果需要,我们可以在这里指定远程网关
$ functions:函数及所在位置等
$ lang:python:使用Docker打包你的功能
$ handler:handler.py的路径
$ image:Docker镜像

10.构建函数:
$ faas-cli build -f ./hello-python.yml 注意每次修改函数需要重新build和deploy
$ faas-cli deploy -f ./hello-python.yml
显示以下命令表示他已准备好:
Deploying: hello-python.
No existing service to remove
Deployed.
200 OK
URL: http://localhost:8080/function/hello-python

11.调用:你可以使用UI或者输入以下命令调用:
$ curl localhost:8080/function/hello-python -d "it’s Alex here"
返回:Hello! You said:its Alex here

12.导入第三方依赖项
比如requests  首先pip install requests
现在我们可以更新我们的Python代码了。让我们这样做它可以接受URL的JSON请求和我们想要测试的字符串:
我们将使用JSON请求触发它,它将采用以下格式:
{
 "url": "https://blog.alexellis.io/rss/",
 "term": "docker"
}

13.现在更新hello-python/handler.py文件:
import requests
import json

def handle(req):
    result = {"found": False}
    json_req = json.loads(req)
    r = requests.get(json_req["url"])
    if json_req["term"] in r.text:
        result = {"found": True}

14.重新部署:
$ faas-cli build -f ./hello-python.yml && \ 
  faas-cli deploy -f ./hello-python.yml

15.测试:使用UI或者以下测试
$ curl localhost:8080/function/hello-python --data-binary '{
 "url": "https://blog.alexellis.io/rss/",
 "term": "docker"
}'

16结果:
{"found": true}
    print json.dumps(result)


版权声明:本文为SuperLillitH原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。