构造请求
请求头
headers={'Accept': 'application/vnd.github.v3.text-match+json'}
res = requests.get(url,headers)
get请求
res = requests.get(url='https://api.github.com/search/repositories')
参数
# res = requests.get(url,params)
# params={'q':'requests+language:python'}
# params=[('q', 'requests+language:python')]
# params=b'q=requests+language:python'
其他请求方法
>>> requests.post('https://httpbin.org/post', data={'key':'value'})
>>> requests.put('https://httpbin.org/put', data={'key':'value'})
>>> requests.delete('https://httpbin.org/delete')
>>> requests.head('https://httpbin.org/get')
>>> requests.patch('https://httpbin.org/patch', data={'key':'value'})
>>> requests.options('https://httpbin.org/get')
消息体
# data={'key':'value'}
# data=[('key', 'value')}
# json={'key':'value'}
响应处理
响应状态码
status = res.status_code
响应头信息(键不分大小写)
requests_header=res.headers['content-type']
响应内容
字节格式查看内容
data = res.content
# b'{\n "current_user_url": "https://api.github.com/user",\n "cur
字符串格式查看内容(序列化JSON)
因为对 bytes 解码到 str 需要一个编码格式,所以如果你没有指定,请求将尝试根据响应头来猜测编码格式
res.encoding = 'utf-8'
data=res.text
# {"current_user_url":"https://api.github.com/user","cur
字典形式内容(反序列化JSON)
data=res.json()
# {'current_user_url': 'https://api.github.com/user', 'curin
提取内容
repository = data['items'][0]
也可以使用 .text 获取 str 并使用json.loads() 对其进行反序列化
json.loads(data)
其他
检查请求
requests 库会在将请求实际发送到目标服务器之前准备该请求。 请求准备包括像验证头信息和序列化JSON内容等
response.request.headers['Content-Type']
response.request.url
response.request.body
身份验证
使用auth 参数,rqeuests 将使用HTTP的基本访问认证方案来应用凭据
>>> from getpass import getpass
>>> requests.get('https://api.github.com/user', auth=('username', getpass()))
成功返回<Response [200]>,失败返回<Response [401]>
HTTPBasicAuth效果同上
>>> from requests.auth import HTTPBasicAuth
>>> from getpass import getpass
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('username', getpass()))
requests 也提供了其他身份验证方法,例如 HTTPDigestAuth 和 HTTPProxyAuth
关闭SSL证书验证
>>> requests.get('https://api.github.com', verify=False)
性能
超时
>>> requests.get('https://api.github.com', timeout=1)
还可以将元组传递给 timeout,第一个元素是连接超时(它允许客户端与服务器建立连接的时间),第二个元素是读取超时(一旦你的客户已建立连接而等待响应的时间)
>>> requests.get('https://api.github.com', timeout=(2, 5))
超时异常
import requests
from requests.exceptions import Timeout
try:
response = requests.get('https://api.github.com', timeout=1)
except Timeout:
print('The request timed out')
else:
print('The request did not time out')
Session对象
Session 用于跨请求保留参数。 例如,如果要跨多个请求使用相同的身份验证,当你的应用程序想要再次连接到同一服务器时,它将重用池中的连接而不是建立新连接。
import requests
from getpass import getpass
with requests.Session() as session:
session.auth = ('username', getpass())
response = session.get('https://api.github.com/user')
最大重试
通过 Transport Adapters,你可以为每个与之交互的服务定义一组配置。 例如,假设你希望所有对于https://api.github.com的请求在最终抛出 ConnectionError 之前重试三次。 你将构建一个 Transport Adapter,设置其 max_retries 参数,并将其装载到现有的 Session
import requests
from requests.adapters import HTTPAdapter
from requests.exceptions import ConnectionError
github_adapter = HTTPAdapter(max_retries=3)
session = requests.Session()
# Use `github_adapter` for all requests to endpoints that start with this URL
session.mount('https://api.github.com', github_adapter)
try:
session.get('https://api.github.com')
except ConnectionError as ce:
print(ce)
结尾
re库参考:https://juejin.im/post/5d8c630e51882511f444f65b