Python多種接口請(qǐng)求方式示例詳解
- 發(fā)送JSON數(shù)據(jù)
如果你需要發(fā)送JSON數(shù)據(jù),可以使用json參數(shù)。這會(huì)自動(dòng)設(shè)置Content-Type為application/json。
highlighter- Go
import requests
import json
url = 'http://example.com/api/endpoint'
data = {
"key": "value",
"another_key": "another_value"
}
headers = {'Content-Type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print(response.status_code)
print(response.json())- 發(fā)送表單數(shù)據(jù) (Form Data)
如果你需要發(fā)送表單數(shù)據(jù),可以使用data參數(shù)。這會(huì)自動(dòng)設(shè)置Content-Type為application/x-www-form-urlencoded。
highlighter- Go
import requests
url = 'http://example.com/api/endpoint'
data = {
"key": "value",
"another_key": "another_value"
}
response = requests.post(url, data=data)
print(response.status_code)
print(response.text)- 發(fā)送文件 (Multipart Form Data)
當(dāng)你需要上傳文件時(shí),通常會(huì)使用files參數(shù)。這會(huì)設(shè)置Content-Type為multipart/form-data。
highlighter- Python
import requests
url = 'http://example.com/api/upload'
file = {'file': ('image.png', open('image.png', 'rb'))}
data = {
'biz': 'temp',
'needCompress': 'true'
}
response = requests.post(url, data=data, files=file)
print(response.status_code)
print(response.text)- 發(fā)送帶有認(rèn)證信息的請(qǐng)求
如果API需要認(rèn)證信息,可以在請(qǐng)求中添加auth參數(shù)。
highlighter- Go
import requests url = 'http://example.com/api/endpoint' username = 'your_username' password = 'your_password' response = requests.get(url, auth=(username, password)) print(response.status_code) print(response.text)
- 處理重定向
你可以選擇是否允許重定向,默認(rèn)情況下requests會(huì)自動(dòng)處理重定向。
highlighter- Python
import requests url = 'http://example.com/api/endpoint' allow_redirects = False response = requests.get(url, allow_redirects=allow_redirects) print(response.status_code) print(response.history)
- 設(shè)置超時(shí)
你可以設(shè)置請(qǐng)求的超時(shí)時(shí)間,防止長(zhǎng)時(shí)間等待響應(yīng)。
highlighter- Python
import requests
url = 'http://example.com/api/endpoint'
timeout = 5
try:
response = requests.get(url, timeout=timeout)
print(response.status_code)
except requests.exceptions.Timeout:
print("The request timed out")- 使用Cookies
如果你需要發(fā)送或接收cookies,可以通過cookies參數(shù)來實(shí)現(xiàn)。
highlighter- Go
import requests
url = 'http://example.com/api/endpoint'
cookies = {'session': '1234567890'}
response = requests.get(url, cookies=cookies)
print(response.status_code)
print(response.cookies)- 自定義Headers
除了默認(rèn)的頭部信息外,你還可以添加自定義的頭部信息。
highlighter- Go
import requests
url = 'http://example.com/api/endpoint'
headers = {
'User-Agent': 'MyApp/0.0.1',
'X-Custom-Header': 'My custom header value'
}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.headers)- 使用SSL驗(yàn)證
對(duì)于HTTPS請(qǐng)求,你可以指定驗(yàn)證證書的方式。
highlighter- Python
import requests url = 'https://example.com/api/endpoint' verify = True # 默認(rèn)情況下,requests會(huì)驗(yàn)證SSL證書 response = requests.get(url, verify=verify) print(response.status_code) 如果你要跳過SSL驗(yàn)證,可以將verify設(shè)置為False。但請(qǐng)注意,這樣做可能會(huì)導(dǎo)致安全問題。 import requests url = 'https://example.com/api/endpoint' verify = False response = requests.get(url, verify=verify) print(response.status_code)
- 上傳多個(gè)文件
有時(shí)你可能需要同時(shí)上傳多個(gè)文件。你可以通過傳遞多個(gè)files字典來實(shí)現(xiàn)這一點(diǎn)。
highlighter- Python
import requests
url = 'http://example.com/api/upload'
files = [
('file1', ('image1.png', open('image1.png', 'rb'))),
('file2', ('image2.png', open('image2.png', 'rb')))
]
data = {
'biz': 'temp',
'needCompress': 'true'
}
response = requests.post(url, data=data, files=files)
print(response.status_code)
print(response.text)- 使用代理
如果你需要通過代理服務(wù)器訪問互聯(lián)網(wǎng),可以使用proxies參數(shù)。
highlighter- Go
import requests
url = 'http://example.com/api/endpoint'
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
response = requests.get(url, proxies=proxies)
print(response.status_code)- 流式下載大文件
當(dāng)下載大文件時(shí),可以使用流式讀取以避免內(nèi)存不足的問題。
highlighter- Python
import requests
url = 'http://example.com/largefile.zip'
response = requests.get(url, stream=True)
with open('largefile.zip', 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)- 分塊上傳大文件
與流式下載類似,你也可以分塊上傳大文件以避免內(nèi)存問題。
highlighter- Python
import requests
url = 'http://example.com/api/upload'
file_path = 'path/to/largefile.zip'
chunk_size = 8192
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(chunk_size), b''):
files = {'file': ('largefile.zip', chunk)}
response = requests.post(url, files=files)
if response.status_code != 200:
print("Error uploading file:", response.status_code)
break- 使用Session對(duì)象
如果你需要多次請(qǐng)求同一個(gè)網(wǎng)站,并且希望保持狀態(tài)(例如使用cookies),可以使用Session對(duì)象。
highlighter- Python
import requests
s = requests.Session()
# 設(shè)置session的cookies
s.cookies['example_cookie'] = 'example_value'
# 發(fā)送GET請(qǐng)求
response = s.get('http://example.com')
# 發(fā)送POST請(qǐng)求
data = {'key': 'value'}
response = s.post('http://example.com/post', data=data)
print(response.status_code)- 處理錯(cuò)誤
處理網(wǎng)絡(luò)請(qǐng)求時(shí),經(jīng)常會(huì)遇到各種錯(cuò)誤??梢允褂卯惓L幚韥韮?yōu)雅地處理這些情況。
highlighter- Python
import requests
url = 'http://example.com/api/endpoint'
try:
response = requests.get(url)
response.raise_for_status() # 如果響應(yīng)狀態(tài)碼不是200,則拋出HTTPError異常
except requests.exceptions.HTTPError as errh:
print(f"Http Error: {errh}")
except requests.exceptions.ConnectionError as errc:
print(f"Error Connecting: {errc}")
except requests.exceptions.Timeout as errt:
print(f"Timeout Error: {errt}")
except requests.exceptions.RequestException as err:
print(f"OOps: Something Else: {err}")- 使用認(rèn)證令牌
許多API使用認(rèn)證令牌進(jìn)行身份驗(yàn)證。你可以將認(rèn)證令牌作為頭部的一部分發(fā)送。
highlighter- Python
import requests
url = 'http://example.com/api/endpoint'
token = 'your_auth_token_here'
headers = {
'Authorization': f'Token {token}'
}
response = requests.get(url, headers=headers)
print(response.status_code)
print(response.json())- 使用OAuth2認(rèn)證
對(duì)于使用OAuth2的API,你需要獲取一個(gè)訪問令牌并將其包含在請(qǐng)求頭中。
highlighter- Python
import requests
# 獲取OAuth2訪問令牌
token_url = 'http://example.com/oauth/token'
data = {
'grant_type': 'client_credentials',
'client_id': 'your_client_id',
'client_secret': 'your_client_secret'
}
response = requests.post(token_url, data=data)
access_token = response.json()['access_token']
# 使用訪問令牌進(jìn)行請(qǐng)求
api_url = 'http://example.com/api/endpoint'
headers = {
'Authorization': f'Bearer {access_token}'
}
response = requests.get(api_url, headers=headers)
print(response.status_code)
print(response.json())來源:https://www.iwmyx.cn/pythondzjkqqfb.html
到此這篇關(guān)于Python多種接口請(qǐng)求方式示例 的文章就介紹到這了,更多相關(guān)Python接口請(qǐng)求方式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中read,readline和readlines的區(qū)別案例詳解
這篇文章主要介紹了Python中read,readline和readlines的區(qū)別案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
用python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的驗(yàn)證碼
這篇文章主要介紹了用python實(shí)現(xiàn)一個(gè)簡(jiǎn)單的驗(yàn)證碼的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-12-12
python定時(shí)任務(wù) sched模塊用法實(shí)例
這篇文章主要介紹了python定時(shí)任務(wù) sched模塊用法實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
python圖片和二進(jìn)制轉(zhuǎn)換的三種實(shí)現(xiàn)方式
本文介紹了將PIL格式、數(shù)組和圖片轉(zhuǎn)換為二進(jìn)制的不同方法,包括使用PIL庫、OpenCV和直接讀取二進(jìn)制,此外,還提到了數(shù)據(jù)傳輸中base64格式的應(yīng)用,這些信息對(duì)需要進(jìn)行圖片數(shù)據(jù)處理和轉(zhuǎn)換的開發(fā)者非常有用2024-09-09
python+openCV對(duì)視頻進(jìn)行截取的實(shí)現(xiàn)
這篇文章主要介紹了python+openCV對(duì)視頻進(jìn)行截取的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
python中time模塊指定格式時(shí)間字符串轉(zhuǎn)為時(shí)間戳
本文主要介紹了python中time模塊指定格式時(shí)間字符串轉(zhuǎn)為時(shí)間戳,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Python中的默認(rèn)參數(shù)實(shí)例分析
這篇文章主要介紹了Python中的默認(rèn)參數(shù)實(shí)例分析,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01

