
2Slides Team
3 min read

Python 是自动化、数据管道和 AI 工作流的首选语言。本教程将向您展示如何使用 Python 调用 2Slides REST API 自动生成演示文稿 — 从简单的单页幻灯片到复杂的自动化流程。
pip install requests python-dotenv
创建一个
.envTWOSLIDES_API_KEY=sk-2slides-your-api-key
import os import time import requests from dotenv import load_dotenv load_dotenv() API_KEY = os.getenv('TWOSLIDES_API_KEY') BASE_URL = 'https://2slides.com/api/v1' HEADERS = { 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' } def generate_slides(topic, theme_id=None, mode='async'): """根据文本主题生成演示文稿。""" payload = { 'userInput': topic, 'mode': mode, 'responseLanguage': 'en', 'resolution': '2K', } if theme_id: payload['themeId'] = theme_id response = requests.post( f'{BASE_URL}/slides/generate', headers=HEADERS, json=payload ) response.raise_for_status() return response.json() def wait_for_job(job_id, timeout=300, interval=3): """轮询直到任务完成。""" start = time.time() while time.time() - start < timeout: response = requests.get( f'{BASE_URL}/jobs/{job_id}', headers=HEADERS ) data = response.json() status = data.get('status') print(f' 任务 {job_id}: {status}') if status == 'success': return data if status == 'failed': raise Exception(f'任务失败: {data}') time.sleep(interval) raise TimeoutError(f'任务 {job_id} 在 {timeout} 秒后超时') # 生成演示文稿 job = generate_slides('Top 10 AI Trends for 2026') print(f'任务 ID: {job["jobId"]}') result = wait_for_job(job['jobId']) print(f'下载链接: {result["downloadUrl"]}')
def convert_file_to_slides(file_url, prompt='', theme_id=None): """将 PDF、DOCX、XLSX 或其他文件转换为幻灯片。""" payload = { 'fileUrl': file_url, 'userInput': prompt, 'mode': 'async' } if theme_id: payload['themeId'] = theme_id response = requests.post( f'{BASE_URL}/slides/create-pdf-slides', headers=HEADERS, json=payload ) response.raise_for_status() job = response.json() return wait_for_job(job['jobId']) # 转换季度报告 PDF result = convert_file_to_slides( file_url='https://your-storage.com/q1-report.pdf', prompt='Executive summary for the board, 10 slides max' ) print(f'下载链接: {result["downloadUrl"]}')
def create_like_this(topic, reference_image_url, resolution='2K'): """生成与参考设计匹配的幻灯片。""" payload = { 'userInput': topic, 'designStyle': { 'global': { 'referenceImageUrl': reference_image_url } }, 'resolution': resolution, 'mode': 'async' } response = requests.post( f'{BASE_URL}/slides/create-like-this', headers=HEADERS, json=payload ) response.raise_for_status() job = response.json() return wait_for_job(job['jobId']) # 匹配您的品牌模板 result = create_like_this( topic='Monthly Team Update — March 2026', reference_image_url='https://your-brand.com/slide-template.png' )
def add_narration(job_id, mode='single', voice='Charon', content_mode='concise'): """为现有幻灯片添加 AI 语音旁白。""" payload = { 'jobId': job_id, 'mode': mode, 'voice': voice, 'contentMode': content_mode } response = requests.post( f'{BASE_URL}/slides/generate-narration', headers=HEADERS, json=payload ) response.raise_for_status() return response.json() def download_with_audio(job_id): """下载包含语音音频文件的幻灯片。""" response = requests.post( f'{BASE_URL}/slides/download-slides-pages-voices', headers=HEADERS, json={'jobId': job_id} ) response.raise_for_status() return response.json()
def search_themes(query=''): """搜索可用的幻灯片主题。""" params = {'query': query} if query else {} response = requests.get( f'{BASE_URL}/themes', headers=HEADERS, params=params ) response.raise_for_status() return response.json() themes = search_themes('corporate') for theme in themes.get('themes', []): print(f"{theme['id']}: {theme['name']}")
""" 自动化周报流程。 通过 cron 运行:0 9 * * MON python weekly_report.py """ import json from datetime import datetime def weekly_report_pipeline(): print(f'正在生成周报: {datetime.now().isoformat()}') # 1. 生成幻灯片 job = generate_slides( topic='''Weekly Engineering Update — Week of March 23, 2026: - Deployed v2.4 to production (99.9% uptime) - 3 new API endpoints shipped - Performance: p99 latency down 40% - Sprint velocity: 42 story points (target: 40) - Next week: database migration, new auth system''', theme_id='corporate-standard-id' ) result = wait_for_job(job['jobId']) print(f'幻灯片已就绪: {result["downloadUrl"]}') # 2. 添加旁白 add_narration(job['jobId'], mode='single', voice='Kore') print('旁白已添加') # 3. 下载打包文件 package = download_with_audio(job['jobId']) print(f'完整打包文件: {json.dumps(package, indent=2)}') return result['downloadUrl'] if __name__ == '__main__': url = weekly_report_pipeline() print(f'\n报告 URL: {url}')
from requests.exceptions import HTTPError, Timeout, ConnectionError def safe_generate(topic, retries=3): """使用重试逻辑生成幻灯片。""" for attempt in range(retries): try: job = generate_slides(topic) return wait_for_job(job['jobId']) except HTTPError as e: if e.response.status_code == 429: wait = 2 ** attempt * 5 # 指数退避 print(f'达到速率限制。等待 {wait} 秒...') time.sleep(wait) elif e.response.status_code == 402: raise Exception('积分不足') else: raise except (Timeout, ConnectionError) as e: print(f'网络错误 (尝试 {attempt + 1} 次): {e}') time.sleep(5) raise Exception(f'在 {retries} 次重试后失败')
Python 3.7+,以支持 f-string 和
requests是的 — 将
requestsaiohttp使用 asyncio 并发运行多个生成任务,同时遵守速率限制(每分钟 60 次请求)。
开始自动化 — 获取您的 2Slides API 密钥 并使用 Python 生成演示文稿。
Create stunning AI-powered presentations in seconds. Transform your ideas into professional slides with 2slides AI Agent.
Try For FreeYour AI Agent for slides. Save time, shine faster with intelligent presentation creation.
© 2026 2slides. All rights reserved.