-
Python云计算-成本优化
自动扩缩容 import boto3def scale_application(): # 监控指标 cpu_utilization = get_cpu_utilization() if cpu_utilization > 80: # 扩容 scale_up() elif cpu_utilization < 20: # 缩容 scale_down() 成本监控 import boto3def get_co...…
-
Python云计算-消息队列
SQS 消息队列 import boto3sqs = boto3.client('sqs')# 发送消息response = sqs.send_message( QueueUrl='https://sqs.region.amazonaws.com/account/queue', MessageBody='Hello World')# 接收消息messages = sqs.receive_message(QueueUrl=queue_url) Redis Pub/Sub imp...…
-
Python云计算-微服务架构
微服务拆分 # 用户服务from flask import Flaskapp = Flask(__name__)@app.route('/users/<user_id>')def get_user(user_id): # 用户逻辑 return {'user_id': user_id} API 网关 from flask import Flask, request, jsonifyapp = Flask(__name__)@app.route('/api/<...…
-
Python云计算-数据服务
S3 操作 import boto3s3 = boto3.client('s3')# 上传文件s3.upload_file('local_file.txt', 'my-bucket', 'remote_file.txt')# 下载文件s3.download_file('my-bucket', 'remote_file.txt', 'local_file.txt') DynamoDB 操作 import boto3dynamodb = boto3.resource('dynamodb'...…
-
Python实用技巧-迭代器与生成器
迭代协议 it = iter([1, 2, 3])print(next(it)) # 1 生成器函数与表达式 def count_up_to(n): i = 1 while i <= n: yield i i += 1nums = list(count_up_to(5)) 管道式组合 total = sum(x*x for x in range(10) if x % 2 == 0) 转载请注明:周志洋的博客 » Python实用技巧-迭代...…
-
Python云计算-无服务器架构
AWS Lambda import jsondef lambda_handler(event, context): # 处理事件 name = event.get('name', 'World') return { 'statusCode': 200, 'body': json.dumps(f'Hello {name}!') } Azure Functions import azure.functions as funcdef main(...…
-
Python云计算-AWS服务
boto3 基础 import boto3# 创建客户端s3 = boto3.client('s3')ec2 = boto3.resource('ec2')# 列出S3存储桶buckets = s3.list_buckets()for bucket in buckets['Buckets']: print(bucket['Name']) EC2 实例管理 # 启动实例instances = ec2.create_instances( ImageId='ami-0c55b159...…
-
Python DevOps-安全实践
依赖安全扫描 # 使用 safety 扫描已知漏洞pip install safetysafety check# 使用 bandit 扫描代码安全问题pip install banditbandit -r myproject/ 密钥管理 import osfrom cryptography.fernet import Fernet# 环境变量管理密钥SECRET_KEY = os.getenv('SECRET_KEY')# 加密敏感数据cipher = Fernet(SECRET_K...…
-
Python DevOps-基础设施即代码
Terraform 基础 provider "aws" { region = "us-west-2"}resource "aws_instance" "web" { ami = "ami-0c55b159cbfafe1d0" instance_type = "t2.micro" tags = { Name = "Python App Server" }} Ansible Playbook - hosts: web_servers become: yes tas...…
-
Python DevOps-Kubernetes部署
Deployment 配置 apiVersion: apps/v1kind: Deploymentmetadata: name: python-appspec: replicas: 3 selector: matchLabels: app: python-app template: metadata: labels: app: python-app spec: containers: - name: python-app ...…
-
Python DevOps-监控与日志
Prometheus 监控 from prometheus_client import Counter, Histogram, start_http_server# 指标定义REQUEST_COUNT = Counter('requests_total', 'Total requests')REQUEST_DURATION = Histogram('request_duration_seconds', 'Request duration')@REQUEST_DURATION.time()...…
-
Python DevOps-CI/CD流水线
GitHub Actions name: CI/CD Pipelineon: [push, pull_request]jobs: test: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: 3.9 - name: Install...…
-
Python DevOps-Docker容器化
Dockerfile 编写 FROM python:3.9-slimWORKDIR /appCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txtCOPY . .EXPOSE 8000CMD ["gunicorn", "app:app", "--bind", "0.0.0.0:8000"] 多阶段构建 # 构建阶段FROM python:3.9 as builderCOPY requireme...…
-
Python机器学习-集成方法
Bagging from sklearn.ensemble import BaggingClassifierbagging = BaggingClassifier( base_estimator=DecisionTreeClassifier(), n_estimators=100, random_state=42) Boosting from sklearn.ensemble import AdaBoostClassifier, GradientBoostingClass...…
-
Python机器学习-超参数调优
网格搜索 from sklearn.model_selection import GridSearchCVparam_grid = { 'C': [0.1, 1, 10, 100], 'gamma': [1, 0.1, 0.01, 0.001]}grid_search = GridSearchCV(SVC(), param_grid, cv=5)grid_search.fit(X_train, y_train) 随机搜索 from sklearn.model_selectio...…
-
Python实用技巧-文件读写与pathlib
文本读写 from pathlib import Pathp = Path("example.txt")p.write_text("你好,世界", encoding="utf-8")content = p.read_text(encoding="utf-8") 二进制读写 data = b"\x00\x01\x02"with open("data.bin", "wb") as f: f.write(data)with open("data.bin", "rb") as f: ...…
-
Python机器学习-模型评估
交叉验证 from sklearn.model_selection import cross_val_score, StratifiedKFold# K折交叉验证cv_scores = cross_val_score(model, X, y, cv=5)print(f"平均准确率: {cv_scores.mean():.3f}")# 分层K折skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42) 评估指标 fr...…
-
Python机器学习-特征工程
特征编码 from sklearn.preprocessing import LabelEncoder, OneHotEncoder# 标签编码le = LabelEncoder()y_encoded = le.fit_transform(y)# 独热编码ohe = OneHotEncoder()X_encoded = ohe.fit_transform(X_categorical) 特征缩放 from sklearn.preprocessing import MinMaxScale...…
-
Python机器学习-深度学习入门
TensorFlow 基础 import tensorflow as tf# 创建模型model = tf.keras.Sequential([ tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax')])# 编译模型model.compile(optimizer='adam', ...…
-
Python机器学习-Scikit-learn进阶
管道使用 from sklearn.pipeline import Pipelinefrom sklearn.preprocessing import StandardScalerfrom sklearn.ensemble import RandomForestClassifierpipeline = Pipeline([ ('scaler', StandardScaler()), ('classifier', RandomForestClassifier())])pipelin...…