跳到主要内容

Python 快速开始

准备工作

在开始之前,请确保您已完成以下准备:

  1. 开通云开发环境开通云开发环境
  2. 获取 API 访问凭证:在 CloudBase 控制台 获取环境 ID 和 API 密钥

更多详情请参考:Python 完整文档

添加 CloudBase AI 开发插件

可选:如果你使用 AI 编程助手(如 Cursor、Claude Code、CodeBuddy 等)进行开发,建议先完成本步骤,让 AI 具备 CloudBase 开发能力。

复制 AI Prompt 粘贴到 AI IDE

在 AI 对话中输入:

帮我把 CloudBase 接好,按下面做:
1. 打开 https://docs.cloudbase.net/skill.md,按说明完成接入。
2. 接入完成后告诉我,并建议最相关的下一步。

查看 skill.md →

使用 Skills 开发

对 AI 说:

使用 CloudBase Skills:在 Python 后端服务中集成 CloudBase HTTP API,包括数据库和存储功能

Skills 使用文档 →

也可以手动安装 CloudBase Skills:

npx skills add tencentcloudbase/cloudbase-skills -y

身份认证

from cloudbase_client import cloudbase

def sign_in(username, password):
"""账号密码登录"""
result = cloudbase.request("POST", "/auth/v1/signin",
json={"username": username, "password": password})

if result:
access_token = result.get("access_token")
refresh_token = result.get("refresh_token")
user_id = result.get("sub")

print(f"登录成功! 用户ID: {user_id}")
print(f"访问令牌: {access_token[:20]}...")
return result
return None

# 使用示例
if __name__ == "__main__":
result = sign_in("your_username", "your_password")

云存储

import os
import requests
from datetime import datetime
from cloudbase_client import cloudbase

def upload_file(file_path, object_id=None):
"""上传文件到云存储"""
if not object_id:
filename = os.path.basename(file_path)
timestamp = int(datetime.now().timestamp() * 1000)
object_id = f"uploads/{timestamp}-{filename}"

# 1. 获取上传信息
upload_info = cloudbase.request("POST", "/v1/storages/get-objects-upload-info",
json=[{"objectId": object_id}])

if not upload_info:
return None

upload_info = upload_info[0]
upload_url = upload_info["uploadUrl"]

try:
# 2. 上传文件
upload_headers = {
"Authorization": upload_info["authorization"],
"X-Cos-Security-Token": upload_info["token"],
"X-Cos-Meta-Fileid": upload_info["cloudObjectMeta"]
}

with open(file_path, "rb") as f:
file_data = f.read()

upload_response = requests.put(upload_url, headers=upload_headers, data=file_data)
upload_response.raise_for_status()

result = {
"cloudObjectId": upload_info["cloudObjectId"],
"downloadUrl": upload_info["downloadUrl"],
"objectId": object_id
}

print("文件上传成功:")
print(f"- 对象ID: {result['objectId']}")
print(f"- 下载URL: {result['downloadUrl']}")

return result

except FileNotFoundError:
print(f"文件不存在: {file_path}")
return None
except Exception as e:
print(f"文件上传失败: {e}")
return None

# 使用示例
if __name__ == "__main__":
result = upload_file("./example.jpg")

云函数

from cloudbase_client import cloudbase

def call_function(function_name, data=None):
"""调用云函数"""
result = cloudbase.request("POST", f"/v1/functions/{function_name}", json=data or {})

if result:
print("云函数调用结果:", result)
return result

# 使用示例
if __name__ == "__main__":
result = call_function("{%FUNCTION_NAME%}")

大模型

import requests
import json
from cloudbase_client import cloudbase

def stream_text(model, sub_model, messages):
"""流式文本生成"""
payload = {
"model": sub_model,
"messages": messages,
"stream": True
}

url = f"{cloudbase.base_url}/v1/ai/{model}/chat/completions"
headers = cloudbase.headers.copy()
headers["Accept"] = "text/event-stream"

try:
response = requests.post(url, headers=headers, json=payload, stream=True)
response.raise_for_status()

print("AI 流式响应:")
full_content = ""

for line in response.iter_lines():
if line:
line_str = line.decode("utf-8")
if line_str.startswith("data: "):
data_str = line_str[6:]
if data_str.strip() != "[DONE]":
try:
chunk_data = json.loads(data_str)
content = chunk_data.get("choices", [{}])[0].get("delta", {}).get("content", "")
if content:
print(content, end="", flush=True)
full_content += content
except json.JSONDecodeError:
continue

print() # 换行
return full_content
except Exception as e:
print(f"AI 调用失败: {e}")
return None

# 使用示例
if __name__ == "__main__":
response = stream_text(
"{%AI_MODEL_NAME%}",
"{%AI_SUB_MODEL_NAME%}",
[
{"role": "system", "content": "请严格按照七言绝句或七言律诗的格律要求创作,平仄需符合规则,押韵要和谐自然,韵脚字需在同一韵部。"},
{"role": "user", "content": "春天"}
]
)