Python
更新时间:2026-09-24
本示例演示用 Python SDK 创建和执行您的 CFC 函数。
安装
- 在 官方网站 下载Python SDK。
- 进入下载目录,解压 SDK 包,并进入包含
setup.py的源码目录。 - 安装 SDK 之前,需要先执行以下命令安装
pycrypto依赖:
Bash
1pip install pycrypto
如当前环境使用 Python 3,也可以执行:
Bash
1pip3 install pycrypto
- 执行以下命令安装 SDK 包:
Bash
1python setup.py install
如当前环境未提供 python 命令,可根据实际 Python 环境执行:
Bash
1python3 setup.py install --user
使用样例
Python
1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4import os
5
6from baidubce.auth.bce_credentials import BceCredentials
7from baidubce.bce_client_configuration import BceClientConfiguration
8from baidubce.services.cfc.cfc_client import CfcClient
9
10function_name = "testHelloWorld" # 您可以自定义函数名
11
12# 创建 CFC 客户端。
13# 可选择的 Endpoint 包括:cfc.bj.baidubce.com、cfc.gz.baidubce.com、cfc.su.baidubce.com。
14host = "<Your Endpoint>"
15access_key_id = "<Your AccessKeyID>"
16access_key_secret = "<Your AccessKeySecret>"
17
18# 也可以通过环境变量的形式获取 AK、SK。
19# access_key_id = os.environ["BCE_ACCESS_KEY_ID"]
20# access_key_secret = os.environ["BCE_ACCESS_KEY_SECRET"]
21
22config = BceClientConfiguration(
23 credentials=BceCredentials(access_key_id, access_key_secret),
24 endpoint=host
25)
26cfc_client = CfcClient(config)
27
28# 下面是您要发布的 zip 包的 base64-encoded 内容。
29# 注意:zip 包压缩时不能包含顶层文件夹目录。
30base64_file = "<Your base64-encoded Code>"
31
32# 创建函数。
33create_response = cfc_client.create_function(
34 function_name,
35 description="CFC SDK Demo",
36 handler="<Your index>.handler",
37 memory_size=128,
38 region="bj",
39 zip_file=base64_file,
40 publish=False,
41 run_time="python2",
42 timeout=3,
43 dry_run=False
44)
45
46# 获取函数 BRN。
47brn = create_response.FunctionBrn
48
49# 执行函数。
50invocations_response = cfc_client.invocations(brn)
51print(invocations_response.read())
52```代码中主要参数说明如下:
53
54| 参数 | 必填 | 说明 |
55| --- | --- | --- |
56| `host` | 是 | CFC 服务 Endpoint,例如 `cfc.bj.baidubce.com`、`cfc.gz.baidubce.com` 或 `cfc.su.baidubce.com`。 |
57| `access_key_id` | 是 | 百度智能云 Access Key ID。建议通过环境变量或安全配置读取。 |
58| `access_key_secret` | 是 | 百度智能云 Secret Access Key。请勿在代码仓库或日志中明文保存。 |
59| `function_name` | 是 | 待创建的 CFC 函数名称,可自定义。 |
60| `handler` | 是 | 函数入口,格式通常为 `<文件名>.handler`,需与代码包中的入口函数保持一致。 |
61| `memory_size` | 是 | 函数内存大小,单位为 MB。 |
62| `region` | 是 | 函数所属地域,例如 `bj`。该值需与所选 Endpoint 对应。 |
63| `zip_file` | 是 | 函数代码 zip 包经过 Base64 编码后的字符串。zip 包压缩时不能包含顶层文件夹目录。 |
64| `publish` | 否 | 是否在创建函数时发布版本。 |
65| `run_time` | 是 | 函数运行时,示例中使用 `python2`。 |
66| `timeout` | 是 | 函数执行超时时间,单位为秒。 |
67| `dry_run` | 否 | 是否仅校验请求而不实际创建函数。 |
68
69`create_function` 调用成功后会返回函数信息,可通过 `create_response.FunctionBrn` 获取函数 BRN。`invocations` 调用会执行该函数,返回结果可通过 `invocations_response.read()` 读取。
评价此篇文章
