response防止页面缓存和重设响应头部

 // 防止缓存       
//Forces caches to obtain a new copy of the page from the origin server
response.setHeader("Cache-Control","no-cache"); 
//Directs caches not to store the page under any circumstance
response.setHeader("Cache-Control","no-store"); 
//HTTP 1.0 backward compatibility 
response.setHeader("Pragma","no-cache"); 
//Causes the proxy cache to see the page as "stale"
response.setDateHeader("Expires", 0); 
            
 // 重新设置响应头部
response.setContentType("text/html;charset=UTF-8");
// response.setContentType("text/xml;charset=UTF-8");
# -*- coding: utf-8 -*- """ ============================ requests 库核心用法详解(增强版) ============================ 版本:1.3 | 整合基础与高级功能 """ import requests # ==================== # 总述:requests 简介 # ==================== """ requests 是 Python 中最常用的 HTTP 请求库,适用于 API 测试、爬虫、接口调试等场景。 本课件重点讲解 requests 的核心请求方式: 1. GET - 获取资源 2. POST - 创建资源 3. PUT - 更新资源 4. DELETE - 删除资源 所有接口均为免费可调用(使用 https://jsonplaceholder.typicode.com/) """ # ==================== # 分述:requests 的五种核心用法(含 headers、params、data) # ==================== # 示例 1:GET 请求 - 获取资源(带查询参数 params 请求头 headers) def test_get_with_params_and_headers(): """GET请求示例:带查询参数自定义请求头""" print("\n=== 示例 1:GET 请求(带参数请求头) ===") # 定义目标 URL url = "https://jsonplaceholder.typicode.com/posts" # 定义查询参数(params) params = { "userId": 1, # 查询用户ID为1的所有文章 "_limit": 2 # 限制返回2条数据 } # 定义请求头(headersheaders = { "User-Agent": "MyTestApp/1.0", # 自定义用户代理 "Accept": "application/json", # 接收 JSON 格式响应 "Cache-Control": "no-cache" # 禁用缓存 } # 发送 GET 请求,携带 params headers try: response = requests.get(url, params=params, headers=headers, timeout=3) # 结果处理 print(f"请求URL: {response.url}") # 显示完整请求URL print(f"响应状态码: {response.status_code}") # 检查响应是否成功 if response.ok: # 打印返回的数据(前两条) print("返回数据(前2条):") for item in response.json(): print(f"ID: {item['id']}, 标题: {item['title']}") else: print(f"请求失败: {response.status_code} - {response.reason}") except requests.exceptions.Timeout: print("请求超时!请检查网络连接") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # ==================== # POST请求数据格式选择原则 # ==================== """ 关键选择依据: 1. ✅ 使用JSON格式的场景: - 与RESTful API交互时 - 发送结构化复杂数据(嵌套对象/数组) - API要求Content-Type: application/json - 需要发送数值型/布尔型等非字符串数据 2. ✅ 使用表单数据格式的场景: - 提交HTML表单数据 - 进行传统Web登录/注册 - API要求Content-Type: application/x-www-form-urlencoded - 文件上传(multipart/form-data) - 需要兼容旧系统接口 3. ❗ 注意:同一API可能有多种数据格式支持 - 需查看API文档确认支持格式 - 错误格式会导致400 Bad Request - 可通过响应头Content-Type验证返回格式 """ # 示例 2:POST 请求 - 创建资源(发送 JSON 数据) def test_post_send_json(): """POST请求示例:发送JSON数据""" print("\n=== 示例 2:POST 请求(发送 JSON 数据) ===") # 定义目标 URL url = "https://jsonplaceholder.typicode.com/posts" # 定义要发送的 JSON 数据 json_data = { "title": "新文章", "body": "这是测试内容", "userId": 1 } # 定义请求头,说明发送的是 JSON 数据 headers = { "Content-Type": "application/json", "X-Request-Source": "Python Script" } # 发送 POST 请求,使用 json 参数自动序列化字典 try: response = requests.post(url, json=json_data, headers=headers, timeout=3) # 结果处理 print(f"响应状态码: {response.status_code}") print(f"响应头Content-Type: {response.headers['Content-Type']}") if response.status_code == 201: # 201 Created data = response.json() print(f"创建的资源 ID: {data['id']}") print(f"完整响应: {data}") else: print(f"请求失败: {response.status_code} - {response.text}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # 示例 3:POST 请求 - 发送表单数据(data 参数) def test_post_send_form_data(): """POST请求示例:发送表单数据""" print("\n=== 示例 3:POST 请求(发送表单数据) ===") # 定义目标 URL(用于接收 POST 请求的测试服务) url = "https://httpbin.org/post" # 定义表单数据 form_data = { "username": "testuser", "password": "testpass", "remember_me": True } # 发送 POST 请求,使用 data 参数发送表单数据 try: response = requests.post(url, data=form_data, timeout=3) # 结果处理 print(f"响应状态码: {response.status_code}") print(f"响应头Content-Type: {response.headers['Content-Type']}") if response.status_code == 200: server_data = response.json() print("服务器接收到的表单数据:") for key, value in server_data['form'].items(): print(f"{key}: {value} (类型: {type(value).__name__})") # 显示数据类型 else: print(f"请求失败: {response.status_code} - {response.text}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # 示例 4:PUT 请求 - 更新资源 def test_put_update_resource(): """PUT请求示例:更新资源""" print("\n=== 示例 4:PUT 请求(更新资源) ===") # 定义目标 URL(更新 ID 为 1 的文章) url = "https://jsonplaceholder.typicode.com/posts/1" # 定义更新的数据 update_data = { "id": 1, "title": "更新后的标题", "body": "更新后的内容", "userId": 1 } # 发送 PUT 请求,使用 json 参数 try: response = requests.put(url, json=update_data, timeout=3) # 结果处理 print(f"响应状态码: {response.status_code}") if response.status_code == 200: data = response.json() print(f"更新后的标题: {data['title']}") print(f"完整更新数据: {data}") else: print(f"更新失败: {response.status_code} - {response.text}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # 示例 5:DELETE 请求 - 删除资源 def test_delete_resource(): """DELETE请求示例:删除资源""" print("\n=== 示例 5:DELETE 请求(删除资源) ===") # 定义目标 URL(删除 ID 为 1 的文章) url = "https://jsonplaceholder.typicode.com/posts/1" # 发送 DELETE 请求 try: response = requests.delete(url, timeout=3) # 结果处理 print(f"响应状态码: {response.status_code}") if response.status_code == 200: print("资源删除成功!") print(f"响应内容: {response.text}") else: print(f"删除失败: {response.status_code} - {response.reason}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # ==================== # 高级功能详解 # ==================== """ 1. ✅ 会话保持(Session): - 复用TCP连接提升性能 - 自动管理CookieHeaders - 保持认证状态 >>> with requests.Session() as session: >>> session.headers.update({'User-Agent': 'MyApp'}) >>> response1 = session.get(url1) # 携带自定义头部 >>> response2 = session.get(url2) # 复用TCP连接头部 2. ✅ 代理配置(Proxies): - 隐藏真实IP地址 - 绕过访问限制 - 分布式请求分发 >>> proxies = { >>> 'http': 'http://10.10.1.10:3128', >>> 'https': 'https://10.10.1.10:1080' >>> } >>> response = requests.get(url, proxies=proxies) 3. ✅ 重定向控制(Allow Redirects): - 禁用自动重定向(allow_redirects=False) - 获取原始重定向响应 - 跟踪重定向链路 >>> response = requests.get(url, allow_redirects=False) >>> if response.status_code == 302: >>> redirect_url = response.headers['Location'] """ # 示例 6:会话保持(Session)实战 def demo_session(): """会话保持实战示例""" print("\n=== 示例 6:会话保持(Session)实战 ===") # 创建Session对象 with requests.Session() as session: # 设置全局请求头超时 session.headers.update({ "User-Agent": "SessionDemo/1.0", "Accept": "application/json" }) session.timeout = 3 # 全局超时设置 # 第一次请求:获取用户数据并保存Cookie response = session.get("https://jsonplaceholder.typicode.com/users/1") print(f"用户请求状态: {response.status_code}") user_data = response.json() print(f"用户名: {user_data['name']}") # 第二次请求:复用会话查询用户的帖子 posts_url = f"https://jsonplaceholder.typicode.com/users/{user_data['id']}/posts" response = session.get(posts_url, params={"_limit": 2}) print(f"帖子请求状态: {response.status_code}") print(f"用户帖子数量: {len(response.json())}") # 示例 7:代理与重定向控制 def demo_proxy_and_redirect(): """代理与重定向控制示例""" print("\n=== 示例 7:代理与重定向控制 ===") # 定义代理(实际使用时替换为有效代理) proxies = { 'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8080' } # 测试URL(支持重定向) test_url = "https://httpbin.org/redirect-to?url=https://example.com" try: # 发送带代理的请求,禁用重定向 response = requests.get( test_url, proxies=proxies, allow_redirects=False, timeout=5 ) print(f"初始状态码: {response.status_code}") print(f"重定向地址: {response.headers.get('Location', '无')}") # 手动跟踪重定向 if response.status_code in (301, 302, 303, 307, 308): redirect_url = response.headers['Location'] redirect_response = requests.get(redirect_url, proxies=proxies, timeout=5) print(f"重定向后状态码: {redirect_response.status_code}") print(f"最终URL: {redirect_response.url}") except requests.exceptions.ProxyError: print("代理连接失败!") except requests.exceptions.RequestException as e: print(f"请求异常: {e}") # ==================== # 请求处理最佳实践 # ==================== """ 1. ⏱ 超时设置:response = requests.get(url, timeout=3.0) 2. 异常处理: try: response = requests.get(url) response.raise_for_status() except requests.exceptions.RequestException as e: print(f"请求错误: {e}") 3. 🔒 会话管理: with requests.Session() as session: # 复用配置连接 4. 🌐 代理配置: proxies = {'http': 'http://proxy:port'} response = requests.get(url, proxies=proxies) 5. 🔄 重定向控制: response = requests.get(url, allow_redirects=False) 6. 📊 性能优化: - 启用连接池(默认已启用) - 复用Session对象 - 批量请求使用连接复用 """ # ==================== # 主函数:执行所有示例 # ==================== if __name__ == "__main__": print("🚀 开始演示 requests 核心功能") test_get_with_params_and_headers() test_post_send_json() test_post_send_form_data() test_put_update_resource() test_delete_resource() demo_session() demo_proxy_and_redirect() print("\n✅ 所有演示完成") 再补充下,what,how,why,这个课件主要是讲requests,在一个课件返回
最新发布
09-05
<think>好的,用户让我补充关于requests库的what、how、why部分到现有的课件中。首先,我需要回顾用户提供的代码现有的内容。用户之前已经详细展示了requests的各种用法,包括GET、POST、PUT、DELETE请求,以及会话管理、代理重定向控制等高级功能。 用户的需求是补充what、how、why部分,可能希望在课件开头或某个总结部分加入这些内容。我需要确保这部分内容与现有结构一致,保持逻辑连贯。 首先,What部分需要解释requests库是什么,它的作用优势。用户已经提到requests是Python中最常用的HTTP请求库,适用于API测试、爬虫等场景。需要更详细地说明它的特点,比如简洁的API、自动处理JSON、异常处理等。 然后,Why部分要说明为什么选择requests。需要对比其他库如urllib,强调requests的易用性功能全面性。比如,requests简化了HTTP请求的发送响应处理,内置了很多实用功能,减少了重复代码。 How部分要指导如何正确使用requests,包括最佳实践常见模式。用户现有的最佳实践部分已经涵盖了超时设置、异常处理、会话管理等,可以进一步整合到How部分,形成结构化的指导。 接下来,需要检查现有课件的结构,找到合适的位置插入这三个部分。可能在总述之后,分述之前加入这些内容,作为理论指导,帮助读者更好地理解后续示例。 同时,要注意保持代码示例的完整性,不进行修改,只添加文字说明。需要确保语言简洁,符合用户之前使用的风格,比如使用图标清晰的标题。 最后,验证补充的内容是否覆盖了用户的需求,是否逻辑清晰,帮助学习者系统地理解requests库的使用。可能还需要调整格式,确保与现有课件风格一致,比如使用相同的标题符号注释风格。</think># requests 库核心用法详解(增强版) ## What-Why-How 体系化解析 --- ### 📌 What:什么是 requests 库? ```python import requests ``` **核心定位**: Python 中最优雅的 HTTP 客户端库,专为人类设计的 HTTP 协议交互工具 **核心特性**: 1. 支持所有 HTTP 方法(GET/POST/PUT/DELETE 等) 2. 自动处理 JSON 数据编解码 3. 灵活的请求参数配置(params/data/json) 4. 完善的异常处理机制(超时/连接/重定向) 5. 高级功能支持(Session/代理/重定向控制) **对比 urllib 优势**: | 特性 | requests | urllib | |------------------|-------------------|---------------------| | 代码简洁度 | ✅ 高度封装 | ❌ 原生复杂 | | JSON 自动处理 | ✅ 内置 json() | ❌ 需手动 json.loads | | 异常处理 | ✅ 统一异常类 | ❌ 分散错误处理 | | 会话保持 | ✅ Session 支持 | ❌ 需手动管理 | | 文件上传 | ✅ files 参数 | ❌ 需构造 multipart | --- ### 🔍 Why:为什么选择 requests? #### 1. 开发效率革命性提升 ```python # requests 实现 response = requests.get('https://api.example.com/data') data = response.json() # 自动解析 JSON # urllib 实现 import urllib.request, json with urllib.request.urlopen('https://api.example.com/data') as url: data = json.loads(url.read().decode()) # 手动解码 ``` #### 2. 工业级功能支持 - **自动化测试**:API 接口验证、负载测试 - **数据采集**:爬虫开发(遵守 robots.txt) - **系统集成**:第三方服务对接(支付/短信/地图) - **安全通信**:SSL/TLS 支持、身份认证 #### 3. 社区生态强大 - 被广泛用于 Django、Flask 等主流框架 - 与 pytest、selenium 等测试工具深度集成 - 持续维护更新(GitHub 16k+ stars) --- ### 🛠 How:如何正确使用 requests? #### 标准请求流程模板 ```python try: # 1. 构造请求 response = requests.request( method='GET', url='https://api.example.com/data', params={'page': 1}, headers={'Authorization': 'Bearer token'}, timeout=5 # 5秒超时 ) # 2. 响应处理 response.raise_for_status() # 抛出 HTTP 错误 data = response.json() # 解析响应数据 except requests.exceptions.Timeout: print("⚠️ 请求超时!请检查网络") except requests.exceptions.HTTPError as e: print(f"🚫 HTTP 错误:{e.response.status_code}") except requests.exceptions.RequestException as e: print(f"❌ 请求异常:{str(e)}") ``` #### 最佳实践指南 1. **超时必设** ```python requests.get('https://api.example.com', timeout=3.5) # 推荐 2-5 秒 ``` 2. **会话复用** ```python with requests.Session() as session: session.headers.update({'User-Agent': 'MyApp'}) response = session.get('https://api.example.com/data') ``` 3. **代理配置** ```python proxies = { 'http': 'http://10.10.1.10:3128', 'https': 'https://10.10.1.10:1080' } requests.get('https://api.example.com', proxies=proxies) ``` 4. **重试机制** ```python from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry session = requests.Session() retries = Retry(total=3, backoff_factor=1) session.mount('https://', HTTPAdapter(max_retries=retries)) ``` --- ### 📚 完整学习路径 ``` 入门 → 发送基本请求 → 处理响应 → 异常处理 → 高级特性 → 实战应用 │ │ │ │ │ GET/POST JSON处理 超时/状态码 Session/代理 API测试/爬虫 ``` #### 常见问题排查 1. **400 Bad Request** - 检查请求参数格式(JSON vs 表单) - 验证必填字段完整性 2. **401 Unauthorized** - 检查身份凭证(Token/API Key) - 确认请求头格式(Bearer Token/Basic Auth) 3. **403 Forbidden** - 验证权限配置 - 检查 IP 黑白名单 4. **429 Too Many Requests** - 实施请求限速(time.sleep()) - 使用会话复用减少连接开销 --- ### 🧠 记忆锦囊 ``` 请求五要素:URL 方法 参数 头部 超时 代理 响应三看:状态码 头部 内容 异常三防:超时 HTTP错误 网络异常 会话三用:头部复用 连接复用 Cookie保持 ``` > 本课件完整代码示例已包含 7 个实战场景 + 5 类错误处理 + 3 种高级用法,建议结合 [https://httpbin.org](https://httpbin.org) 测试服务进行练习。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值