自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

揭秘Python中的JSON數(shù)據(jù)格式與Requests模塊

開發(fā)
JSON數(shù)據(jù)格式和Requests模塊在現(xiàn)代編程中扮演著不可或缺的角色。JSON作為一種輕量級(jí)的數(shù)據(jù)交換格式,廣泛應(yīng)用于Web服務(wù)之間的數(shù)據(jù)傳輸;而Requests庫則是Python中最流行的HTTP客戶端庫,用于發(fā)起HTTP請(qǐng)求并與服務(wù)器交互。

引言:

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)容!

責(zé)任編輯:華軒 來源: 測(cè)試開發(fā)學(xué)習(xí)交流
相關(guān)推薦

2014-08-12 10:15:42

數(shù)據(jù)格式JSONXML

2010-01-06 13:23:20

JSON數(shù)據(jù)格式

2010-01-06 14:04:55

Json數(shù)據(jù)格式

2024-11-12 12:08:06

JSON數(shù)據(jù)技巧

2009-09-07 19:02:07

JSON是什么

2013-03-27 10:51:44

iOSjson解析網(wǎng)絡(luò)交互數(shù)據(jù)格式解析

2011-04-11 09:48:59

AjaxWEB服務(wù)

2017-03-27 14:58:03

MapReduce數(shù)據(jù)類型數(shù)據(jù)格式

2022-06-05 14:57:35

發(fā)送釘釘運(yùn)維架構(gòu)

2019-07-22 08:49:37

PythonJSON編程語言

2009-03-09 09:34:56

AjaxHTMLJavaScript

2024-12-19 00:12:02

APIJSON數(shù)據(jù)

2024-05-08 16:54:21

Python編程開發(fā)

2010-03-22 14:58:35

2018-09-18 11:16:11

MapReduceXML大數(shù)據(jù)

2021-11-11 23:16:33

前端數(shù)據(jù)格式Web

2024-05-16 13:40:23

Python編程

2025-01-13 12:46:31

SpringBootJacksonJSON

2011-04-11 13:14:58

AjaxWEB服務(wù)

2010-07-09 10:42:38

HART協(xié)議
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)