揭秘Python中的JSON数据格式与Requests模块

开发
JSON数据格式和Requests模块在现代编程中扮演着不可或缺的角色。JSON作为一种轻量级的数据交换格式,广泛应用于Web服务之间的数据传输;而Requests库则是Python中最流行的HTTP客户端库,用于发起HTTP请求并与服务器交互。

引言:

JSON数据格式和Requests模块在现代编程中扮演着不可或缺的角色。JSON作为一种轻量级的数据交换格式,广泛应用于Web服务之间的数据传输;而Requests库则是Python中最流行的HTTP客户端库,用于发起HTTP请求并与服务器交互。今天,我们将通过10个精选的代码示例,一同深入了解这两个重要工具的使用。

1.创建并解析JSON数据

import json
# 创建JSON数据
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
json_data = json.dumps(data)  # 将Python对象转换为JSON字符串
print(json_data)  # 输出:{"name": "John", "age": 30, "city": "New York"}
# 解析JSON数据
json_string = '{"name": "Jane", "age": 28, "city": "San Francisco"}'
parsed_data = json.loads(json_string)  # 将JSON字符串转换为Python字典
print(parsed_data)  # 输出:{'name': 'Jane', 'age': 28, 'city': 'San Francisco'}

2.使用Requests发送GET请求

import requests
response = requests.get('https://api.github.com')
print(response.status_code)  # 输出HTTP状态码,如:200
print(response.json())  # 输出响应体内容(假设响应是JSON格式)
# 保存完整的响应信息
with open('github_response.json', 'w') as f:
    json.dump(response.json(), f)

3.发送带参数的GET请求

params = {'q': 'Python requests', 'sort': 'stars'}
response = requests.get('https://api.github.com/search/repositories', params=params)
repos = response.json()['items']
for repo in repos[:5]:  # 打印前5个搜索结果
    print(repo['full_name'])

4.发送POST请求

payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://httpbin.org/post', jsnotallow=payload, headers=headers)
print(response.json())

5.设置超时时间

requests.get('http://example.com', timeout=5)  # 设置超时时间为5秒

6.处理Cookies

# 保存cookies
response = requests.get('http://example.com')
cookies = response.cookies
# 发送带有cookies的请求
requests.get('http://example.com', cookies=cookies)

7.自定义HTTP头部信息

headers = {'User-Agent': 'My-Custom-UA'}
response = requests.get('http://httpbin.org/headers', headers=headers)
print(response.text)

8.下载文件

url = 'https://example.com/image.jpg'
response = requests.get(url)
# 写入本地文件
with open('image.jpg', 'wb') as f:
    f.write(response.content)

9.处理身份验证

from requests.auth import HTTPBasicAuth
response = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))

10.重试机制

from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# 创建一个重试策略
retry_strategy = Retry(
    total=3,
    status_forcelist=[429, 500, 502, 503, 504],
    backoff_factor=1,
)
# 添加重试策略到适配器
adapter = HTTPAdapter(max_retries=retry_strategy)
# 将适配器添加到会话
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get('https://example.com')

结语:

通过上述10个Python中JSON数据格式与Requests模块的实战示例,相信您对它们的使用有了更为深入的理解。熟练掌握这两种工具将极大提升您在Web开发、API调用等方面的生产力。请持续关注我们的公众号,获取更多Python和其他编程主题的精彩内容!

责任编辑:华轩 来源: 测试开发学习交流
相关推荐

2014-08-12 10:15:42

数据格式JSONXML

2010-01-06 13:23:20

JSON数据格式

2010-01-06 14:04:55

Json数据格式

2009-09-07 19:02:07

JSON是什么

2011-04-11 09:48:59

AjaxWEB服务

2013-03-27 10:51:44

iOSjson解析网络交互数据格式解析

2017-03-27 14:58:03

MapReduce数据类型数据格式

2022-06-05 14:57:35

发送钉钉运维架构

2019-07-22 08:49:37

PythonJSON编程语言

2009-03-09 09:34:56

AjaxHTMLJavaScript

2010-03-22 14:58:35

2018-09-18 11:16:11

MapReduceXML大数据

2021-11-11 23:16:33

前端数据格式Web

2016-11-10 13:00:32

网络传输协议pythonhttp

2011-04-11 13:14:58

AjaxWEB服务

2010-07-09 10:27:33

SQL Server数

2010-07-09 10:42:38

HART协议

2017-03-10 10:16:37

PythonRequests库

2011-03-07 15:01:42

MySQLXML数据

2011-04-07 10:15:00

AjaxWeb
点赞
收藏

51CTO技术栈公众号