揭秘Python中的JSON數(shù)據(jù)格式與Requests模塊
引言:
JSON數(shù)據(jù)格式和Requests模塊在現(xiàn)代編程中扮演著不可或缺的角色。JSON作為一種輕量級(jí)的數(shù)據(jù)交換格式,廣泛應(yīng)用于Web服務(wù)之間的數(shù)據(jù)傳輸;而Requests庫則是Python中最流行的HTTP客戶端庫,用于發(fā)起HTTP請(qǐng)求并與服務(wù)器交互。今天,我們將通過10個(gè)精選的代碼示例,一同深入了解這兩個(gè)重要工具的使用。
1.創(chuàng)建并解析JSON數(shù)據(jù)
import json
# 創(chuàng)建JSON數(shù)據(jù)
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data) # 將Python對(duì)象轉(zhuǎn)換為JSON字符串
print(json_data) # 輸出:{"name": "John", "age": 30, "city": "New York"}
# 解析JSON數(shù)據(jù)
json_string = '{"name": "Jane", "age": 28, "city": "San Francisco"}'
parsed_data = json.loads(json_string) # 將JSON字符串轉(zhuǎn)換為Python字典
print(parsed_data) # 輸出:{'name': 'Jane', 'age': 28, 'city': 'San Francisco'}
2.使用Requests發(fā)送GET請(qǐng)求
import requests
response = requests.get('https://api.github.com')
print(response.status_code) # 輸出HTTP狀態(tài)碼,如:200
print(response.json()) # 輸出響應(yīng)體內(nèi)容(假設(shè)響應(yīng)是JSON格式)
# 保存完整的響應(yīng)信息
with open('github_response.json', 'w') as f:
json.dump(response.json(), f)
3.發(fā)送帶參數(shù)的GET請(qǐng)求
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個(gè)搜索結(jié)果
print(repo['full_name'])
4.發(fā)送POST請(qǐng)求
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.設(shè)置超時(shí)時(shí)間
requests.get('http://example.com', timeout=5) # 設(shè)置超時(shí)時(shí)間為5秒
6.處理Cookies
# 保存cookies
response = requests.get('http://example.com')
cookies = response.cookies
# 發(fā)送帶有cookies的請(qǐng)求
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.處理身份驗(yàn)證
from requests.auth import HTTPBasicAuth
response = requests.get('https://example.com/api', auth=HTTPBasicAuth('username', 'password'))
10.重試機(jī)制
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
# 創(chuàng)建一個(gè)重試策略
retry_strategy = Retry(
total=3,
status_forcelist=[429, 500, 502, 503, 504],
backoff_factor=1,
)
# 添加重試策略到適配器
adapter = HTTPAdapter(max_retries=retry_strategy)
# 將適配器添加到會(huì)話
session = requests.Session()
session.mount('http://', adapter)
session.mount('https://', adapter)
response = session.get('https://example.com')
結(jié)語:
通過上述10個(gè)Python中JSON數(shù)據(jù)格式與Requests模塊的實(shí)戰(zhàn)示例,相信您對(duì)它們的使用有了更為深入的理解。熟練掌握這兩種工具將極大提升您在Web開發(fā)、API調(diào)用等方面的生產(chǎn)力。請(qǐng)持續(xù)關(guān)注我們的公眾號(hào),獲取更多Python和其他編程主題的精彩內(nèi)容!