# SCF
腾讯云 SCF (opens new window) 支持 Python (opens new window)、Node.js、Golang、PHP、Java 等语言,可选地区列表可参考支持地域 (opens new window)。
SCF 将在函数接收到触发请求时执行函数,SCF 平台负责所有函数的生命周期 (opens new window)。
API 网关触发器将下线 (opens new window),替代方案为函数 URL (opens new window)。
# 函数类型
云函数 SCF 提供了代码部署 (opens new window)、镜像部署 (opens new window)两种部署方式 (opens new window)。
# Web 函数
Web 函数 (opens new window)下,API 网关会在 header 里加上函数触发所需要的信息,并将原始请求直接透传,触发后端函数运行。
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000)
# Event 函数
Event 函数 (opens new window)下,API 网关会将请求内容以参数形式传递给函数,并将函数返回作为响应返回给请求方。
import json
def main_handler(event, context):
print("Received event: " + json.dumps(event, indent = 2))
print("Received context: " + str(context))
print("Hello world")
return("Hello World")
# 部署方式
# Plugin
腾讯已不再维护此方式。
Plugin 部署方式仅支持 Event 函数。
serverless-tencent-scf (opens new window) 插件提供 Serverless Framework (opens new window) 对 Tencent SCF (opens new window) 的支持。
更多触发器的配置可参考 serverless.yml (opens new window)。
# Components
腾讯已不再维护此方式。
Serverless Components (opens new window) 是 Serverless Framework (opens new window) 重磅推出的基础设施编排能力,支持开发者通过 Serverless Components 构建,组合并部署你的 Serverless 应用。
可以通过基础组件部署相关的资源,如 tencent-scf (opens new window) 可以部署云函数,tencent-cos (opens new window) 可以部署一个存储桶;封装的上层组件实际上是对基础组件的组合,并且增加一些额外的逻辑,实现一些高阶功能,如 tencent-django (opens new window) 就通过对请求的 WSGI 转换,将 Django 框架部署到云函数上,其底层依赖了 tencent-scf/tencent-apigateway 等组件。
目前腾讯云的基础组件包括:
- @serverless/tencent-scf (opens new window)
- @serverless/tencent-cos (opens new window)
- @serverless/tencent-cdn (opens new window)
- @serverless/tencent-apigateway (opens new window)
- @serverless/tencent-cam-role (opens new window)
- @serverless/tencent-cam-policy (opens new window)
封装的上层组件包括:
- @serverless/tencent-express (opens new window)
- @serverless/tencent-django (opens new window)
- @serverless/tencent-egg (opens new window)
- @serverless/tencent-flask (opens new window)
- @serverless/tencent-koa (opens new window)
- @serverless/tencent-laravel (opens new window)
- @serverless/tencent-website (opens new window)
相关例子:
# SCF
serverless-tencent (opens new window) 基于 Component 的方式,进行了一些封装,目前已弃用 (opens new window)。
serverless-cloud-framework (opens new window) 是 serverless-tencent (opens new window) 的继任版本 (opens new window)。
安装 serverless-cloud-framework (opens new window):
npm i -g serverless-cloud-framework
# .env
TENCENT_SECRET_ID=xxxxxxxxxx
TENCENT_SECRET_KEY=xxxxxxxx
serverless.yml 配置项可参考 @serverless-components/tencent-scf (opens new window)。
@tencentyun/serverless-demo (opens new window) 也有许多模板可供参考。
#!/bin/bash
SERVERLESS=1 /var/lang/python39/bin/python3.9 -u run.py
部署函数:
scf deploy --noCache
# 运行环境
# 层
SCF 中的层 (opens new window)用于管理依赖库或公共代码文件。
打包 Python 依赖:
pip install -r requirements.txt -t ./runtime