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入門for循環(huán)嵌套理解學(xué)習(xí)
這篇文章主要介紹了python入門關(guān)于for循環(huán)嵌套的理解學(xué)習(xí),希望大家可以學(xué)會(huì)并運(yùn)用到日常工作中,有需要的朋友可以借鑒參考下,希望能夠有幫助2021-09-09
scrapy在python爬蟲中搭建出錯(cuò)的解決方法
在本篇文章里小編給大家整理了一篇關(guān)于scrapy在python爬蟲中搭建出錯(cuò)的解決方法,有需要的朋友們可以學(xué)習(xí)參考下。2020-11-11
pandas數(shù)據(jù)篩選和csv操作的實(shí)現(xiàn)方法
這篇文章主要介紹了pandas數(shù)據(jù)篩選和csv操作的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
pytorch教程實(shí)現(xiàn)mnist手寫數(shù)字識(shí)別代碼示例
這篇文章主要講解了pytorch教程中如何實(shí)現(xiàn)mnist手寫數(shù)字識(shí)別,文中附有詳細(xì)的代碼示例,test準(zhǔn)確率98%,有需要的朋友可以借鑒參考下2021-09-09
Django Form 實(shí)時(shí)從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)的操作方法
這篇文章主要介紹了Django Form 實(shí)時(shí)從數(shù)據(jù)庫(kù)中獲取數(shù)據(jù)的相關(guān)知識(shí),本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07
baselines示例程序train_cartpole.py的ImportError
這篇文章主要為大家介紹了baselines示例程序train_cartpole.py的ImportError引入錯(cuò)誤詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
python通過paramiko復(fù)制遠(yuǎn)程文件及文件目錄到本地
這篇文章主要為大家詳細(xì)介紹了python通過paramiko復(fù)制遠(yuǎn)程文件及文件目錄到本地,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04

