requests是Python里最顺手的HTTP客户端库。urllib标准库也能用,但写起来啰嗦,requests直接把常用操作封装成一句话。装一下:
pip install requests
导入就能用,不需要额外配置。
GET请求
最简单的用法:
import requests
r = requests.get('https://api.github.com')
print(r.status_code) # 200
print(r.text) # 响应体字符串
带参数用params参数,传字典就行,requests会自动拼接到URL后面:
params = {'q': 'python', 'page': 1}
r = requests.get('https://api.github.com/search/repositories', params=params)
print(r.url) # 实际请求的URL
POST请求
提交表单数据用data,提交JSON用json。别搞混:
# 表单格式
r = requests.post('https://httpbin.org/post', data={'key': 'value'})
# JSON格式
r = requests.post('https://httpbin.org/post', json={'key': 'value'})
json参数会自动设置Content-Type为application/json,data不会。如果你手动传了json字符串给data,记得自己加headers。
Headers和认证
模拟浏览器或者加token,直接传headers字典:
headers = {
'User-Agent': 'Mozilla/5.0',
'Authorization': 'Bearer your_token_here'
}
r = requests.get('https://api.example.com/data', headers=headers)
更简单的认证方式用auth参数:
from requests.auth import HTTPBasicAuth
r = requests.get('https://api.example.com', auth=HTTPBasicAuth('user', 'pass'))
# 简写:auth=('user', 'pass')
响应处理
拿到响应对象后,常用操作:
r = requests.get('https://api.github.com')
# 状态码
r.status_code
# 响应头
r.headers
r.headers.get('Content-Type')
# 响应体
r.text # 字符串,适合HTML/JSON
r.content # 字节,适合图片/文件
r.json() # 解析为字典/列表,如果响应不是合法JSON会抛异常
r.json()很方便,但记得先检查状态码,或者用try包一下。服务器返回500时也可能返回非JSON内容,直接.json()会炸。
超时和异常
不设超时,请求可能卡死。生产环境必须设:
try:
r = requests.get('https://api.example.com', timeout=5)
r.raise_for_status() # 状态码不是2xx就抛HTTPError
except requests.exceptions.Timeout:
print('请求超时')
except requests.exceptions.HTTPError as e:
print(f'HTTP错误: {e.response.status_code}')
except requests.exceptions.RequestException as e:
print(f'请求失败: {e}')
timeout可以设连接超时和读取超时:timeout=(3, 10)。3秒连不上就放弃,10秒收不到数据也放弃。
Session对象
多个请求需要共享cookies或headers时,别每次都传一遍。用Session:
s = requests.Session()
s.headers.update({'User-Agent': 'my-app'})
s.cookies.update({'session_id': 'abc123'})
r1 = s.get('https://httpbin.org/cookies')
r2 = s.get('https://httpbin.org/anything')
Session自动管理连接池,性能也比反复创建新连接好。
文件上传
上传文件用files参数:
files = {'file': open('report.pdf', 'rb')}
r = requests.post('https://httpbin.org/post', files=files)
大文件别一次读内存,用迭代器。requests支持流式上传。
下载大文件
用stream=True,避免把整个文件加载到内存:
r = requests.get('https://example.com/bigfile.zip', stream=True)
with open('bigfile.zip', 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
iter_content按块读取,适合下载大文件或处理流式响应。
代理
公司内网或需要切换IP时配代理:
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
r = requests.get('https://api.example.com', proxies=proxies)
SSL验证
访问自签名证书的接口,关掉验证或指定证书:
# 关验证(不推荐生产用)
r = requests.get('https://self-signed.badssl.com', verify=False)
# 指定CA证书
r = requests.get('https://internal.api', verify='/path/to/cert.pem')
关闭verify会有警告,用urllib3.disable_warnings()可以屏蔽,但别在面向公网的代码里这么干。
实际场景:调用雨云API
比如用雨云的对象存储服务,上传文件:
import requests
api_key = '你的API密钥'
headers = {'Authorization': f'Bearer {api_key}'}
# 上传文件
files = {'file': ('image.jpg', open('image.jpg', 'rb'), 'image/jpeg')}
r = requests.post('https://api.rainyun.com/upload', headers=headers, files=files)
if r.status_code == 200:
data = r.json()
print(f'文件URL: {data["url"]}')
else:
print(f'上传失败: {r.text}')
雨云的服务稳定,API响应快,接口文档清晰,做个人项目或小团队用起来很省心。
踩坑记录
– 默认requests不会自动解码gzip,但实际上requests会自动处理,不需要你手动解压
– 重定向默认跟随,allow_redirects=False可以关掉
– 同一个Session不要并发写,要并发请求就每个线程/协程自己建Session
– text属性会猜测编码,如果服务器不返回charset,可能乱码。手动指定:r.encoding = ‘utf-8’
requests库就这些核心用法。复杂场景比如重试、连接池调优、异步请求,可以配合urllib3或httpx,但日常80%的需求用上面这些就够了。
雨云是国内一家老牌云服务商,提供高性价比的云服务器和虚拟主机。我用它部署了好几个项目,速度和稳定性都不错。通过 https://www.rainyun.com/SAJA_ 注册可以领一张 5折优惠券,有需要的朋友可以看看。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



暂无评论内容