热门角色不仅是灵感来源,更是你的效率助手。通过精挑细选的角色提示词,你可以快速生成高质量内容、提升创作灵感,并找到最契合你需求的解决方案。让创作更轻松,让价值更直接!
我们根据不同用户需求,持续更新角色库,让你总能找到合适的灵感入口。
指导用户在指定编程语言中使用库或API完成特定任务,提供分步骤示例代码和可选说明,帮助开发者快速实现功能并掌握调用方法。
下面给出一份从零到一的示例,展示如何用 Python 3.11 + requests 分页拉取用户列表,合并所有页结果,提取所需字段,按 id 去重并导出为 UTF-8 CSV。同时演示 Bearer 鉴权、全局 Session 复用、请求超时、指数退避重试(含 429/5xx 处理)与自定义 User-Agent。
BASE_URL = "https://api.example.com/v1/users" # 替换为你的真实用户列表 API API_KEY = os.environ.get("EXAMPLE_API_KEY", "demo-token")
def get_with_retry(session, url, params=None, retries=5, base_delay=0.5, timeout=10): """ 带指数退避与抖动的 GET 请求。 - 对 429/5xx 进行重试,尊重 Retry-After(秒)头。 - 其他网络错误也会按指数退避重试。 """ for attempt in range(retries): try: resp = session.get(url, params=params, timeout=timeout) # 针对 429(限流)优先处理 if resp.status_code == 429: if attempt == retries - 1: resp.raise_for_status() retry_after = resp.headers.get("Retry-After") if retry_after and retry_after.isdigit(): delay = float(retry_after) else: delay = base_delay * (2 ** attempt) delay += random.uniform(0, 0.25) # 抖动 time.sleep(delay) continue
# 对 5xx 进行重试
if 500 <= resp.status_code < 600:
if attempt == retries - 1:
resp.raise_for_status()
delay = base_delay * (2 ** attempt) + random.uniform(0, 0.25)
time.sleep(delay)
continue
resp.raise_for_status()
return resp
except requests.RequestException:
if attempt == retries - 1:
raise
delay = base_delay * (2 ** attempt) + random.uniform(0, 0.25)
time.sleep(delay)
def get_page(session, page, limit=50): """ 拉取单页。假定分页参数为 page/limit,返回 JSON。 """ params = {"page": page, "limit": limit} resp = get_with_retry(session, BASE_URL, params=params) return resp.json()
def main(): # 全局会话,复用连接 session = requests.Session() session.headers.update({ "Authorization": f"Bearer {API_KEY}", "Accept": "application/json", "User-Agent": "example-client/1.0 (+https://your-domain.example)" })
all_users = []
page = 1
per_page = 50
while True:
data = get_page(session, page, per_page)
# 约定服务端返回 { "items": [ ... ] };若你的 API 字段名不同,请相应调整
items = data.get("items", [])
if not items:
break
for u in items:
all_users.append({
"id": u.get("id"),
"name": u.get("name"),
"email": u.get("email", ""),
"created_at": u.get("created_at", "")
})
page += 1
# 轻微限速,避免触发限流。若服务端限流严格可适当增加间隔
time.sleep(0.2)
# 按 id 去重:保留首个出现的记录
seen = set()
deduped = []
for u in all_users:
uid = u.get("id")
if uid is None:
continue
if uid not in seen:
seen.add(uid)
deduped.append(u)
# 导出为 UTF-8 CSV(含表头)
out_path = "users.csv"
with open(out_path, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["id", "name", "email", "created_at"])
writer.writeheader()
writer.writerows(deduped)
print(f"Wrote {len(deduped)} users to {out_path}")
if name == "main": main()
可选说明与最佳实践
下面给出一套可直接复制运行的示例,使用 Node.js 18 + axios + form-data 在服务端以 multipart/form-data 上传本地图片,包含 Bearer 鉴权、30 秒超时、流式进度统计、最大体积控制与指数退避重试(3 次),成功后打印文件 ID。
const fs = require('fs'); const path = require('path'); const axios = require('axios'); const FormData = require('form-data');
const FILE_PATH = path.resolve(__dirname, 'sample.png'); const API_URL = 'https://api.example.com/v1/files'; const TOKEN = process.env.EXAMPLE_TOKEN || 'demo-token';
// 最大体积控制(可通过环境变量覆盖),默认 20MB const MAX_SIZE_MB = Number(process.env.MAX_SIZE_MB || 20);
function assertFileOK() {
if (!fs.existsSync(FILE_PATH)) {
throw new Error(File not found: ${FILE_PATH});
}
const stat = fs.statSync(FILE_PATH);
const maxBytes = MAX_SIZE_MB * 1024 * 1024;
if (stat.size > maxBytes) {
throw new Error(File too large: ${(stat.size / 1024 / 1024).toFixed(2)}MB > ${MAX_SIZE_MB}MB);
}
return stat;
}
function shouldRetry(err) { // 网络类错误 if (err && err.code && ['ECONNRESET', 'ETIMEDOUT', 'EAI_AGAIN', 'ENOTFOUND', 'ECONNREFUSED', 'EPIPE'].includes(err.code)) { return true; } // HTTP 状态码:5xx 或 429 重试 const status = err && err.response && err.response.status; return status >= 500 || status === 429; }
async function uploadOnce() { const stat = assertFileOK();
const stream = fs.createReadStream(FILE_PATH);
let loaded = 0;
stream.on('data', chunk => {
loaded += chunk.length;
const percent = stat.size ? ((loaded / stat.size) * 100).toFixed(1) : '...';
process.stdout.write(\rUploading ${percent}%);
});
const form = new FormData(); form.append('file', stream, { filename: path.basename(FILE_PATH) }); form.append('meta', JSON.stringify({ folder: 'images', tags: ['guide', 'api'] }));
// 尝试计算 Content-Length(部分服务端要求) const contentLength = await new Promise(resolve => { form.getLength((err, length) => { if (err) return resolve(undefined); resolve(length); }); });
const headers = {
...form.getHeaders(),
'Authorization': Bearer ${TOKEN},
};
if (contentLength !== undefined) headers['Content-Length'] = contentLength;
const res = await axios.post(API_URL, form, { headers, maxBodyLength: Infinity, // 避免 axios 在大文件时提前拦截 timeout: 30000, // 30 秒超时 validateStatus: s => s >= 200 && s < 300 });
console.log('\nFile ID:', res.data && res.data.id); return res.data; }
async function uploadWithRetry(max = 3) {
let lastErr;
for (let i = 0; i < max; i++) {
try {
const data = await uploadOnce();
return data;
} catch (err) {
lastErr = err;
const canRetry = shouldRetry(err);
const wait = 500 * Math.pow(2, i) + Math.floor(Math.random() * 250); // 指数退避 + 抖动
const statusMsg = err && err.response ? (HTTP ${err.response.status}) : '';
console.warn(\nAttempt ${i + 1} failed${statusMsg}${canRetry ? , retrying in ${wait}ms... : ', not retryable.'});
if (!canRetry || i === max - 1) break;
await new Promise(r => setTimeout(r, wait));
}
}
if (lastErr && lastErr.response && lastErr.response.data) {
console.error('Server response:', lastErr.response.data);
} else {
console.error(lastErr && lastErr.message ? lastErr.message : lastErr);
}
throw new Error('All retries failed');
}
uploadWithRetry(3) .then(() => console.log('Done')) .catch(() => process.exit(1));
${API_URL}/${fileId}, {
headers: { Authorization: Bearer ${TOKEN} },
timeout: 10000
});
console.log('File status:', check.data.status, 'meta:', check.data.meta);补充说明
下面给出一套可直接复用的高性能调用模板,展示如何在 Go 1.21 中使用 net/http + context 并发拉取商品详情,开启全局连接复用与 HTTP/2,设置整体与单请求超时,JSON 解码后按价格排序并稳定打印。
步骤 1:初始化项目
步骤 2:编写 main.go 将以下代码保存为 main.go。注意:示例 URL 为占位,请替换为你的真实 API 基址;如需鉴权,请设置环境变量 EXAMPLE_TOKEN。
package main
import ( "context" "encoding/json" "fmt" "net" "net/http" "os" "sort" "sync" "time" )
type Product struct {
ID int json:"id"
Name string json:"name"
Price float64 json:"price"
}
func fetch(ctx context.Context, client *http.Client, id int) (Product, error) { url := fmt.Sprintf("https://api.example.com/v1/products/%d", id) // TODO: 替换为真实接口 req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return Product{}, err }
// 常用请求头:JSON、鉴权、UA
req.Header.Set("Accept", "application/json")
req.Header.Set("User-Agent", "apiguide/1.0 (+https://example.com)")
if token := os.Getenv("EXAMPLE_TOKEN"); token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := client.Do(req)
if err != nil {
return Product{}, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return Product{}, fmt.Errorf("status %d", resp.StatusCode)
}
var p Product
if err := json.NewDecoder(resp.Body).Decode(&p); err != nil {
return Product{}, err
}
return p, nil
}
func main() { // 全局 Transport:连接池、Keep-Alive、HTTP/2、超时参数 tr := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: (&net.Dialer{ Timeout: 3 * time.Second, // TCP 连接超时 KeepAlive: 30 * time.Second, // 保持连接心跳 }).DialContext, ForceAttemptHTTP2: true, // 对支持 ALPN 的 TLS 主机启用 HTTP/2 MaxIdleConns: 100, // 全局最大空闲连接 MaxIdleConnsPerHost: 20, // 每主机最大空闲连接(按并发规模调优) MaxConnsPerHost: 0, // 0 表示不限制 IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 5 * time.Second, ExpectContinueTimeout: 1 * time.Second, // ResponseHeaderTimeout 可选:上限等待首包时间(也可依赖每请求的 context) // ResponseHeaderTimeout: 4 * time.Second, }
// 复用单例 http.Client(不要为每个请求创建新 client)
client := &http.Client{
Transport: tr,
// 不设置 Client.Timeout,改用 context 控制单请求和整体超时,避免双重超时冲突
}
// 需要拉取的商品 ID
ids := []int{101, 205, 309, 412, 518}
// 整体超时(所有请求的总预算时间)
ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
defer cancel()
var (
wg sync.WaitGroup
mu sync.Mutex
products = make([]Product, 0, len(ids))
)
for _, id := range ids {
id := id // 闭包捕获
wg.Add(1)
go func() {
defer wg.Done()
// 单请求超时(连接、TLS、首包、读取等都受此 ctx 控制)
cctx, ccancel := context.WithTimeout(ctx, 3*time.Second)
defer ccancel()
if p, err := fetch(cctx, client, id); err == nil {
mu.Lock()
products = append(products, p)
mu.Unlock()
} else {
// 需求:单请求失败或超时忽略;如需排查可打印到 stderr
// fmt.Fprintf(os.Stderr, "fetch %d error: %v\n", id, err)
}
}()
}
wg.Wait()
// 稳定排序与稳定打印:价格降序;同价时按 ID 升序再按名称升序,确保结果稳定
sort.Slice(products, func(i, j int) bool {
if products[i].Price == products[j].Price {
if products[i].ID == products[j].ID {
return products[i].Name < products[j].Name
}
return products[i].ID < products[j].ID
}
return products[i].Price > products[j].Price
})
for _, p := range products {
fmt.Printf("%d\t%s\t%.2f\n", p.ID, p.Name, p.Price)
}
// 可选:程序退出前显式关闭空闲连接
// tr.CloseIdleConnections()
}
步骤 3:运行与验证
步骤 4:行为说明与关键点
可选优化与扩展
帮助开发者快速掌握如何在特定编程语言中调用指定的库或API,以高效完成具体任务。这一过程中,重点在于提供清晰的指导与代码示例,降低学习曲线并提升开发效率。
帮助入门开发者快速掌握特定编程语言中的库或API使用技巧,从基础任务入手提升实践能力。
为经验丰富的程序员提供复杂任务的清晰实现路径,节省时间、提升技术应用效率。
为讲师设计课程内容时提供可靠开发案例,构建结构清晰的教学素材。
将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。
把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。
在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。
半价获取高级提示词-优惠即将到期