DEMO_PUT_GET

/*
     跟printf的区别
     1,自动换行,不用换行符
     2,printf支持多样化输出,Puts就是输出字符串

*/


#include <stdio.h>

int main()

{
    
 char c;

 puts("请输入一个字符"); 
 c = getchar();
 puts("你输入的字符是"); 
 putchar(c);
 
 return 0;
}

# -*- coding: utf-8 -*- """ ============================ requests 课件:HTTP 请求核心方法详解 ============================ 版本:3.1 | 修复 JSON 解码错误 + 最佳实践示例 📌 使用的免费测试接口: 1. https://jsonplaceholder.typicode.com/ - 提供标准 REST API 接口 2. https://postman-echo.com/post - 稳定的 POST 测试接口,支持表单提交 """ # 🧠 What:requests 是什么? # requests 是 Python 中最常用的 HTTP 客户端库,用于向 Web 服务器发送各种类型的请求。 # 它广泛应用于 API 调试、接口测试、网络爬虫等场景。 # 🛠 How:怎么使用? # - 使用 requests.get() 发送 GET 请求 # - 使用 requests.post() 发送 POST 请求 # - 使用 requests.put() 发送 PUT 请求 # - 使用 requests.delete() 发送 DELETE 请求 # - 使用 params、data、json 控制请求体 # - 使用 headers 设置请求头 # - 使用 timeout 控制超时时间 # - 使用异常处理保障程序健壮性 # 🎯 Why:为什么要用 requests? # - 简洁易用,语法直观 # - 支持多种 HTTP 方法 # - 自动处理编码和解码 # - 社区活跃,文档丰富 # - 适用于自动化脚本、接口测试、爬虫等 # -*- coding: utf-8 -*- """ ============================ requests 课件:HTTP 请求核心方法详解 ============================ 版本:3.1 | 修复 JSON 解码错误 + 最佳实践示例 """ import requests import json # 示例 1:最基础的 GET 请求 def demo_get_simple(): print("=== 示例 1:最基础的 GET 请求 ===") url = "http://127.0.0.1:5000/get" response = requests.get(url) print(f"状态码: {response.status_code}") print("响应内容(前50字符):") print(response.text[:50] + "...") # 示例 2:带查询参数的 GET 请求 def demo_get_with_params(): print("=== 示例 2:带查询参数的 GET 请求 ===") url = "http://127.0.0.1:5000/get" params = { "userId": 1, "_limit": 2 } response = requests.get(url, params=params) print(f"完整URL: {response.url}") result = response.json() print("服务器收到的查询参数:") for key, value in result['params'].items(): print(f"{key}: {value}") # 示例 3:带请求头的 GET 请求 def demo_get_with_headers(): print("=== 示例 3:带请求头的 GET 请求 ===") url = "http://127.0.0.1:5000/get" headers = { "User-Agent": "MyApp/1.0", "Accept": "application/json" } response = requests.get(url, headers=headers) result = response.json() print("请求头信息:") for key, value in result['headers'].items(): print(f"{key}: {value}") # 示例 4:带超时和异常处理的 GET 请求 def demo_get_with_timeout(): print("=== 示例 4:带超时和异常处理的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts" try: response = requests.get(url, timeout=3) response.raise_for_status() print("请求成功,返回数据条数:", len(response.json())) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # 示例 5:最基础的 POST 请求(JSON 数据) def demo_post_simple_json(): print("=== 示例 5:最基础的 POST 请求(JSON 数据) ===") url = "http://127.0.0.1:5000/post-json" data = { "title": "新文章", "body": "这是内容", "userId": 1 } response = requests.post(url, json=data) result = response.json() print("服务器收到的 JSON 数据:") print(json.dumps(result['json'], indent=2)) # 示例 6:POST 发送表单数据(使用支持 form 数据返回的接口) def demo_post_form_data(): print("\n=== 示例 6:POST 发送表单数据 ===") url = "http://127.0.0.1:5000/post-form" form_data = { "username": "demo_user", "email": "user@example.com", "subscribe": "true", "preferences": "tech,news" } try: print(f"📤 发送的表单数据: {form_data}") response = requests.post(url, data=form_data, timeout=5) response.raise_for_status() result = response.json() print("\n✅ 服务器接收到的表单数据:") print(json.dumps(result['form'], indent=2)) print("\n🔍 请求详情:") print(f"请求头: {json.dumps(result['headers'], indent=2)[:100]}...") except requests.exceptions.RequestException as e: print(f"❌ 请求失败: {e}") except json.JSONDecodeError: print("❌ 响应不是有效JSON") print(f"原始响应: {response.text[:200]}") # 示例 7:POST 发送 JSON + 自定义 Headers def demo_post_json_with_headers(): print("=== 示例 7:POST 发送 JSON + 自定义 Headers ===") url = "http://127.0.0.1:5000/post-json" data = { "title": "高级文章", "body": "带自定义头", "userId": 1 } headers = { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest" } response = requests.post(url, json=data, headers=headers) result = response.json() print("服务器收到的 JSON 数据:") print(json.dumps(result['json'], indent=2)) # 示例 8:POST 发送 JSON + 超时和异常处理 def demo_post_with_timeout(): print("=== 示例 8:POST 发送 JSON + 超时和异常处理 ===") url = "https://jsonplaceholder.typicode.com/posts" data = { "title": "测试超时", "body": "超时测试内容", "userId": 1 } try: response = requests.post(url, json=data, timeout=3) response.raise_for_status() print("创建成功,ID:", response.json()['id']) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.RequestException as e: print(f"请求失败: {e}") # 示例 9:使用 PUT 请求更新资源 def demo_put_update(): print("=== 示例 9:使用 PUT 请求更新资源 ===") url = "http://127.0.0.1:5000/put" data = { "id": 1, "title": "更新后的标题", "body": "更新后的内容", "userId": 1 } response = requests.put(url, json=data) result = response.json() print(f"状态码: {response.status_code}") print("服务器收到的数据:") print(json.dumps(result['data'], indent=2)) # 示例 10:使用 DELETE 请求删除资源 def demo_delete_resource(): print("=== 示例 10:使用 DELETE 请求删除资源 ===") url = "http://127.0.0.1:5000/delete" response = requests.delete(url) print(f"状态码: {response.status_code}") print("服务器响应内容:", response.json()) # 示例 11:最佳实践 - 完整请求流程(headers + timeout + session + 异常处理) def demo_best_practice(): print("=== 示例 11:最佳实践 - 完整请求流程 ===") url = "http://127.0.0.1:5000/post-json" headers = { "User-Agent": "BestPracticeApp/1.0", "Accept": "application/json" } data = { "title": "最佳实践文章", "body": "这是一篇测试文章", "userId": 1 } with requests.Session() as session: session.headers.update(headers) try: response = session.post(url, json=data, timeout=5) response.raise_for_status() result = response.json() print("文章创建成功,提交的数据为:") print(json.dumps(result['json'], indent=2)) except requests.exceptions.Timeout: print("请求超时,请检查网络") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求异常: {e}") # 主函数:运行所有示例 if __name__ == "__main__": print("🚀 开始演示 requests 核心请求方法详解") demo_get_simple() demo_get_with_params() demo_get_with_headers() demo_get_with_timeout() demo_post_simple_json() demo_post_form_data() demo_post_json_with_headers() demo_post_with_timeout() demo_put_update() demo_delete_resource() demo_best_practice() print("\n✅ 所有演示完成") 文件中加下注释,并且备注下,form-data 和json这两个 什么时候用哪个
09-05
好的!以下是**完整版 `lesson_requests.py` 文件**,并在文件中添加了详细的注释,包括 `form-data` 和 `JSON` 的使用说明和适用场景。 --- # ✅ 完整代码(含详细注释) ```python # -*- coding: utf-8 -*- """ ============================ requests 课件:HTTP 请求核心方法详解 ============================ 版本:3.1 | 修复 JSON 解码错误 + 最佳实践示例 📌 使用的免费测试接口: 1. https://jsonplaceholder.typicode.com/ - 提供标准 REST API 接口 2. https://postman-echo.com/post - 稳定的 POST 测试接口,支持表单提交 🧠 What:requests 是什么? - requests 是 Python 中最常用的 HTTP 客户端库,用于向 Web 服务器发送各种类型的请求。 - 它广泛应用于 API 调试、接口测试、网络爬虫等场景。 🛠 How:怎么使用? - 使用 requests.get() 发送 GET 请求 - 使用 requests.post() 发送 POST 请求 - 使用 requests.put() 发送 PUT 请求 - 使用 requests.delete() 发送 DELETE 请求 - 使用 params、data、json 控制请求体 - 使用 headers 设置请求头 - 使用 timeout 控制超时时间 - 使用异常处理保障程序健壮性 🎯 Why:为什么要用 requests? - 简洁易用,语法直观 - 支持多种 HTTP 方法 - 自动处理编码和解码 - 社区活跃,文档丰富 - 适用于自动化脚本、接口测试、爬虫等 📌 form-data 和 JSON 的区别与使用场景说明: form-data(表单数据): - 用于网页表单提交,如登录、注册 - 支持上传文件(multipart/form-data) - 数据格式为键值对,常用于传统后端接口 - 使用 requests.post(url, data=...) 提交 JSON: - 用于现代 API 接口通信(如 RESTful API) - 数据结构更复杂,支持嵌套对象、数组 - 通常前后端都使用 JSON 格式传输数据 - 使用 requests.post(url, json=...) 提交 📌 如何选择? - 提交网页表单或上传文件 → 用 form-data - 前后端通信、API 接口 → 用 JSON """ import requests import json # 示例 1:最基础的 GET 请求 def demo_get_simple(): print("=== 示例 1:最基础的 GET 请求 ===") url = "http://127.0.0.1:5000/get" response = requests.get(url) print(f"状态码: {response.status_code}") print("响应内容(前50字符):") print(response.text[:50] + "...") # 示例 2:带查询参数的 GET 请求 def demo_get_with_params(): print("=== 示例 2:带查询参数的 GET 请求 ===") url = "http://127.0.0.1:5000/get" params = { "userId": 1, "_limit": 2 } response = requests.get(url, params=params) print(f"完整URL: {response.url}") result = response.json() print("服务器收到的查询参数:") for key, value in result['params'].items(): print(f"{key}: {value}") # 示例 3:带请求头的 GET 请求 def demo_get_with_headers(): print("=== 示例 3:带请求头的 GET 请求 ===") url = "http://127.0.0.1:5000/get" headers = { "User-Agent": "MyApp/1.0", "Accept": "application/json" } response = requests.get(url, headers=headers) result = response.json() print("请求头信息:") for key, value in result['headers'].items(): print(f"{key}: {value}") # 示例 4:带超时和异常处理的 GET 请求 def demo_get_with_timeout(): print("=== 示例 4:带超时和异常处理的 GET 请求 ===") url = "https://jsonplaceholder.typicode.com/posts" try: response = requests.get(url, timeout=3) response.raise_for_status() print("请求成功,返回数据条数:", len(response.json())) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求错误: {e}") # 示例 5:最基础的 POST 请求(JSON 数据) def demo_post_simple_json(): print("=== 示例 5:最基础的 POST 请求(JSON 数据) ===") url = "http://127.0.0.1:5000/post-json" data = { "title": "新文章", "body": "这是内容", "userId": 1 } response = requests.post(url, json=data) result = response.json() print("服务器收到的 JSON 数据:") print(json.dumps(result['json'], indent=2)) # 示例 6:POST 发送表单数据(使用支持 form 数据返回的接口) def demo_post_form_data(): print("\n=== 示例 6:POST 发送表单数据 ===") url = "http://127.0.0.1:5000/post-form" form_data = { "username": "demo_user", "email": "user@example.com", "subscribe": "true", "preferences": "tech,news" } try: print(f"📤 发送的表单数据: {form_data}") response = requests.post(url, data=form_data, timeout=5) response.raise_for_status() result = response.json() print("\n✅ 服务器接收到的表单数据:") print(json.dumps(result['form'], indent=2)) print("\n🔍 请求详情:") print(f"请求头: {json.dumps(result['headers'], indent=2)[:100]}...") except requests.exceptions.RequestException as e: print(f"❌ 请求失败: {e}") except json.JSONDecodeError: print("❌ 响应不是有效JSON") print(f"原始响应: {response.text[:200]}") # 示例 7:POST 发送 JSON + 自定义 Headers def demo_post_json_with_headers(): print("=== 示例 7:POST 发送 JSON + 自定义 Headers ===") url = "http://127.0.0.1:5000/post-json" data = { "title": "高级文章", "body": "带自定义头", "userId": 1 } headers = { "Content-Type": "application/json", "X-Requested-With": "XMLHttpRequest" } response = requests.post(url, json=data, headers=headers) result = response.json() print("服务器收到的 JSON 数据:") print(json.dumps(result['json'], indent=2)) # 示例 8:POST 发送 JSON + 超时和异常处理 def demo_post_with_timeout(): print("=== 示例 8:POST 发送 JSON + 超时和异常处理 ===") url = "https://jsonplaceholder.typicode.com/posts" data = { "title": "测试超时", "body": "超时测试内容", "userId": 1 } try: response = requests.post(url, json=data, timeout=3) response.raise_for_status() print("创建成功,ID:", response.json()['id']) except requests.exceptions.Timeout: print("请求超时!") except requests.exceptions.RequestException as e: print(f"请求失败: {e}") # 示例 9:使用 PUT 请求更新资源 def demo_put_update(): print("=== 示例 9:使用 PUT 请求更新资源 ===") url = "http://127.0.0.1:5000/put" data = { "id": 1, "title": "更新后的标题", "body": "更新后的内容", "userId": 1 } response = requests.put(url, json=data) result = response.json() print(f"状态码: {response.status_code}") print("服务器收到的数据:") print(json.dumps(result['data'], indent=2)) # 示例 10:使用 DELETE 请求删除资源 def demo_delete_resource(): print("=== 示例 10:使用 DELETE 请求删除资源 ===") url = "http://127.0.0.1:5000/delete" response = requests.delete(url) print(f"状态码: {response.status_code}") print("服务器响应内容:", response.json()) # 示例 11:最佳实践 - 完整请求流程(headers + timeout + session + 异常处理) def demo_best_practice(): print("=== 示例 11:最佳实践 - 完整请求流程 ===") url = "http://127.0.0.1:5000/post-json" headers = { "User-Agent": "BestPracticeApp/1.0", "Accept": "application/json" } data = { "title": "最佳实践文章", "body": "这是一篇测试文章", "userId": 1 } with requests.Session() as session: session.headers.update(headers) try: response = session.post(url, json=data, timeout=5) response.raise_for_status() result = response.json() print("文章创建成功,提交的数据为:") print(json.dumps(result['json'], indent=2)) except requests.exceptions.Timeout: print("请求超时,请检查网络") except requests.exceptions.HTTPError as e: print(f"HTTP 错误: {e}") except requests.exceptions.RequestException as e: print(f"请求异常: {e}") # 主函数:运行所有示例 if __name__ == "__main__": print("🚀 开始演示 requests 核心请求方法详解") demo_get_simple() demo_get_with_params() demo_get_with_headers() demo_get_with_timeout() demo_post_simple_json() demo_post_form_data() demo_post_json_with_headers() demo_post_with_timeout() demo_put_update() demo_delete_resource() demo_best_practice() print("\n✅ 所有演示完成") ``` --- ## ✅ `form-data` 与 `JSON` 使用总结 | 类型 | 使用方式 | 用途说明 | 推荐场景 | |------------|----------------------|------------------------------------|----------------------------------| | `form-data` | `requests.post(url, data=...)` | 提交网页表单、上传文件 | 登录、注册、文件上传 | | `JSON` | `requests.post(url, json=...)` | 发送结构化数据,用于 API 接口通信 | RESTful API、前后端分离、数据嵌套 | --- ##
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值