requests 库最佳实践速查表
一、基本用法
1.发送 GET
请求
import requestsresponse = requests.get("https://example.com/api")
2.发送 POST
请求
import requestsresponse = requests.post("https://example.com/api", json={"param": "value"})
-
json=...
自动帮你加上Content-Type: application/json
头。 -
如果用
data=...
则默认发表单数据(application/x-www-form-urlencoded
)。
二、处理响应内容
目标 | 代码 | 说明 |
读取文本响应 | response.text | 纯文本(str) |
读取JSON响应 | response.json() | 自动解析成python字典 |
读取二进制文件(音频、图片等) | response.content | 原始字节流 |
三、设置请求头(headers)
import requestsheaders = {# "Authorization": "Bearer 你的AP请求头键 作用# Authorization 身份验证:告诉 fal.ai 你是谁,验证你有权限使用这个模型。I密钥"# Bearer 是一种标准的认证类型,意思是你在这里携带了一个访问令牌(Token)。"Authorization": f"Bearer {API_KEY}","Content-Type": "application/json"
}
response = requests.get(url, headers=headers)
四、处理异常(important)
import requeststry:response = requests.post(url, json=data, headers=headers)response.raise_for_status() # 检查是否返回错误状态码data = response.json()
except requests.exceptions.HTTPError as e:print("HTTP 错误:", e)
except requests.exceptions.RequestException as e:print("请求失败:", e)
五、文件下载完整模板
1.下载并保存文件(适合音频、图片、视频)
import requestsurl = "https://example.com/file.wav"
response = requests.get(url)
with open("file.wav", "wb") as f:f.write(response.content)
2.较大文件分块下载(大文件)
import requestswith requests.get(url, stream=True) as r:r.raise_for_status()with open("file.wav", "wb") as f:for chunk in r.iter_content(chunk_size=8192):f.write(chunk)
六、常用参数
参数 | 说明 | 示例 |
timeout | 请求超时 | requests.get(url, timeout=5) |
verify | 关闭 SSL 证书验证(不安全,慎用) | verify=False |
proxies | 使用代理 | proxies={'http': 'http://proxy.com:8080'} |
七、小技巧:封装通用函数
def api_post(url, data, headers=None):try:response = requests.post(url, json=data, headers=headers)response.raise_for_status()return response.json()except requests.exceptions.RequestException as e:print("请求失败:", e)return None
所有API都可以同意用这个调用(前提是用requests调用的,SDK另外写)