欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python多種接口請求方式示例詳解

 更新時間:2024年08月09日 09:12:18   作者:武穆逸仙  
這篇文章主要介紹了Python多種接口請求方式示例?,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下
  • 發(fā)送JSON數(shù)據

如果你需要發(fā)送JSON數(shù)據,可以使用json參數(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ù)據 (Form Data)

如果你需要發(fā)送表單數(shù)據,可以使用data參數(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)

當你需要上傳文件時,通常會使用files參數(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)
  • 設置超時

你可以設置請求的超時時間,防止長時間等待響應。

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設置為False。但請注意,這樣做可能會導致安全問題。
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)
  • 使用代理

如果你需要通過代理服務器訪問互聯(lián)網,可以使用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)
  • 流式下載大文件

當下載大文件時,可以使用流式讀取以避免內存不足的問題。

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)
  • 分塊上傳大文件

與流式下載類似,你也可以分塊上傳大文件以避免內存問題。

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對象

如果你需要多次請求同一個網站,并且希望保持狀態(tài)(例如使用cookies),可以使用Session對象。

highlighter- Python

import requests
s = requests.Session()
# 設置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)
  • 處理錯誤

處理網絡請求時,經常會遇到各種錯誤。可以使用異常處理來優(yōu)雅地處理這些情況。

highlighter- Python

import requests
url = 'http://example.com/api/endpoint'
try:
    response = requests.get(url)
    response.raise_for_status()  # 如果響應狀態(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

到此這篇關于Python多種接口請求方式示例 的文章就介紹到這了,更多相關Python接口請求方式內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論