代码示例指南
本文档展示了各种编程语言的代码示例,用于测试代码块的复制功能和翻译保护。
JavaScript 示例
以下是一个简单的 API 调用示例:
// 获取用户列表
async function fetchUsers() {
const response = await fetch('/api/users', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
});
if (!response.ok) {
throw new Error('获取用户失败');
}
return response.json();
}
// 使用示例
const users = await fetchUsers();
console.log('用户数量:', users.length);
Python 示例
使用 Python 连接数据库:
import pymysql
from contextlib import contextmanager
@contextmanager
def get_connection():
"""获取数据库连接"""
conn = pymysql.connect(
host='localhost',
user='admin',
password='your_password',
database='enterprise_db',
charset='utf8mb4'
)
try:
yield conn
finally:
conn.close()
# 查询示例
with get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE status = %s", ('active',))
results = cursor.fetchall()
print(f"找到 {len(results)} 个活跃用户")
YAML 配置示例
Kubernetes 部署配置:
apiVersion: apps/v1
kind: Deployment
metadata:
name: enterprise-api
namespace: production
labels:
app: enterprise-api
version: v1.0.0
spec:
replicas: 3
selector:
matchLabels:
app: enterprise-api
template:
metadata:
labels:
app: enterprise-api
spec:
containers:
- name: api
image: registry.example.com/enterprise-api:1.0.0
ports:
- containerPort: 8080
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: db-secrets
key: url
resources:
limits:
cpu: "500m"
memory: "512Mi"
requests:
cpu: "200m"
memory: "256Mi"
Shell 脚本示例
自动化部署脚本:
#!/bin/bash
# 部署脚本
set -e
echo "开始部署..."
# 拉取最新代码
git pull origin main
# 安装依赖
npm install
# 构建项目
npm run build
# 重启服务
pm2 restart enterprise-api
echo "部署完成!"
SQL 示例
创建用户表:
-- 创建用户表
CREATE TABLE users (
id BIGINT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(50) NOT NULL UNIQUE,
email VARCHAR(100) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
status ENUM('active', 'inactive', 'suspended') DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_status (status),
INDEX idx_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户表';
-- 插入测试数据
INSERT INTO users (username, email, password_hash) VALUES
('admin', 'admin@example.com', 'hashed_password_here'),
('user1', 'user1@example.com', 'hashed_password_here');
JSON 配置示例
API 响应格式:
{
"code": 200,
"message": "success",
"data": {
"users": [
{
"id": 1,
"name": "张三",
"email": "zhangsan@example.com",
"role": "admin"
},
{
"id": 2,
"name": "李四",
"email": "lisi@example.com",
"role": "user"
}
],
"pagination": {
"page": 1,
"pageSize": 10,
"total": 100
}
}
}
TypeScript 示例
类型定义和接口:
// 用户接口定义
interface User {
id: number;
username: string;
email: string;
role: 'admin' | 'user' | 'guest';
createdAt: Date;
}
// API 响应类型
interface ApiResponse<T> {
code: number;
message: string;
data: T;
}
// 用户服务类
class UserService {
private baseUrl: string;
constructor(baseUrl: string) {
this.baseUrl = baseUrl;
}
async getUser(id: number): Promise<ApiResponse<User>> {
const response = await fetch(`${this.baseUrl}/users/${id}`);
return response.json();
}
async createUser(user: Omit<User, 'id' | 'createdAt'>): Promise<ApiResponse<User>> {
const response = await fetch(`${this.baseUrl}/users`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user)
});
return response.json();
}
}
总结
以上示例展示了常见编程语言的代码片段。在翻译过程中,这些代码块应该保持原样不被翻译,只有注释和字符串中的中文内容可能需要翻译。