Python多種接口請求方式示例詳解
- 發(fā)送JSON數(shù)據(jù)
如果你需要發(fā)送JSON數(shù)據(jù),可以使用json參數(shù)。這會自動設(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ù)。這會自動設(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)你需要上傳文件時,通常會使用files參數(shù)。這會設(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ā)送帶有認證信息的請求
如果API需要認證信息,可以在請求中添加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)
- 處理重定向
你可以選擇是否允許重定向,默認情況下requests會自動處理重定向。
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è)置請求的超時時間,防止長時間等待響應(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ù)來實現(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
除了默認的頭部信息外,你還可以添加自定義的頭部信息。
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驗證
對于HTTPS請求,你可以指定驗證證書的方式。
highlighter- Python
import requests url = 'https://example.com/api/endpoint' verify = True # 默認情況下,requests會驗證SSL證書 response = requests.get(url, verify=verify) print(response.status_code) 如果你要跳過SSL驗證,可以將verify設(shè)置為False。但請注意,這樣做可能會導(dǎo)致安全問題。 import requests url = 'https://example.com/api/endpoint' verify = False response = requests.get(url, verify=verify) print(response.status_code)
- 上傳多個文件
有時你可能需要同時上傳多個文件。你可以通過傳遞多個files字典來實現(xià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)下載大文件時,可以使用流式讀取以避免內(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對象
如果你需要多次請求同一個網(wǎng)站,并且希望保持狀態(tài)(例如使用cookies),可以使用Session對象。
highlighter- Python
import requests
s = requests.Session()
# 設(shè)置session的cookies
s.cookies['example_cookie'] = 'example_value'
# 發(fā)送GET請求
response = s.get('http://example.com')
# 發(fā)送POST請求
data = {'key': 'value'}
response = s.post('http://example.com/post', data=data)
print(response.status_code)- 處理錯誤
處理網(wǎng)絡(luò)請求時,經(jīng)常會遇到各種錯誤??梢允褂卯惓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}")- 使用認證令牌
許多API使用認證令牌進行身份驗證。你可以將認證令牌作為頭部的一部分發(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認證
對于使用OAuth2的API,你需要獲取一個訪問令牌并將其包含在請求頭中。
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']
# 使用訪問令牌進行請求
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多種接口請求方式示例 的文章就介紹到這了,更多相關(guān)Python接口請求方式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中read,readline和readlines的區(qū)別案例詳解
這篇文章主要介紹了Python中read,readline和readlines的區(qū)別案例詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-09-09
python圖片和二進制轉(zhuǎn)換的三種實現(xiàn)方式
本文介紹了將PIL格式、數(shù)組和圖片轉(zhuǎn)換為二進制的不同方法,包括使用PIL庫、OpenCV和直接讀取二進制,此外,還提到了數(shù)據(jù)傳輸中base64格式的應(yīng)用,這些信息對需要進行圖片數(shù)據(jù)處理和轉(zhuǎn)換的開發(fā)者非常有用2024-09-09
python中time模塊指定格式時間字符串轉(zhuǎn)為時間戳
本文主要介紹了python中time模塊指定格式時間字符串轉(zhuǎn)為時間戳,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02

