Skip to main content

从零部署构建 Faas (Function As A Service)

· 4 min read

关键术语

  • Python 函数- 可重复使用的代码块,用于接收输入、处理和返回输出。基本的构建模块。
  • Python Fire- 一个从任何 Python 对象或函数自动生成 CLI 的库,使其成为一个可定制的命令行工具。
  • 命令行界面 (CLI)- 基于文本的用户界面,通过键入提示和输入执行命令。实现自动化。
  • 云函数- 无需管理服务器即可执行代码,以响应 HTTP 或数据库变化等事件。
  • Azure 功能- 微软云托管的无服务器计算服务,用于执行事件驱动功能。
  • 持续集成Continuous Integration)--通过将开发人员提交的代码合并到主线分支(由推送请求触发),对代码更改进行自动测试和验证。

从零构建 Python 函数并部署

创建

  • 创建 GitHub repository
  • 创建 Colab 里面的 Jupyter 笔记,连接 GitHub repository
  • 创建 GitHub Codespace 来编写代码,初始化项目设置(pylint, pytest, Makefile etc.)
  • 设置 GitHub Action

一个函数可以被用在很多地方来做应用:

代码

  • 写逻辑代码: Python
  • 写逻辑代码测试: Pytest
  • 写逻辑代码触发 CLI: Click
  • 写触发 CLI 的逻辑代码测试: Pytest + Click

以上 CLI 部分可以使用 Python Fire 包自动生成 CLI: Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

部署

  • 在 GitHub Codesapce 里面使用 fastAPI 快速部署服务器,获得临时运行的服务器后端用语测试
  • 在 AWS Cloud 9 里面获取 GitHub 代码,构建容器并存储到 AWS ECR 中,使用 AWS App Runner 服务启动 AWS ECR 中的容器

用 Python File 构建 Python NLP 项目

nlplogic/corenlp.py

from textblob import TextBlob
import wikipedia


def search_wikipedia(name):
"""Search wikipedia"""
print(f"Searching for name: {name}")
return wikipedia.search(name)


def summarize_wikipedia(name):
"""Summarize wikipedia"""

print(f"Finding wikipedia summary for name: {name}")
return wikipedia.summary(name)


def get_text_blob(text):
"""Gets text blob object and returns"""

blob = TextBlob(text)
return blob


def get_phrases(name):
"""Find wikipedia name and return back phrases"""

text = summarize_wikipedia(name)
blob = get_text_blob(text)
phrases = blob.noun_phrases
return phrases

Google Cloud Functions

Trigger for dev

  • Click test button with data in testing tab of GCP UI
  • CLI gcloud functi ons call translate-wikipedia --data '{"entity": "facebook", "sentences": "20", "language": "es"}'

Azure Function App

VsCode Azure Functions Plugin to deploy codes from locally.

  • Create New Project first (App level)
  • src folder with functions source codes

test

  • test in Azure UI
  • CLI curl --verbose --header "Content-Type: application/json" -X POST --data '["text": "string"}' https://demo-rust-alfredo-2.azurewebsites.net/api/token

Resources