使用 requests 进行 Basic Authentication
Basic Authentication 是 Web API 最简单的认证方式,工作方式就像登录网站。要获得访问权限,您需要在每个请求中附带您的用户名和密码。API 会使用这组凭据识别您的身份,并允许您访问所请求的数据。
我们先看看当认证失败时服务器如何响应,然后再用 Basic Authentication 来修复它。
重要提示:
- 已经导入了
requests包。 - 您可以使用用户名
[email protected]和密码Warp_ExtrapolationsForfeited2进行认证。
本练习是课程的一部分
Python 中的 API 入门
交互式实操练习
通过完成这段示例代码来试试这个练习。
response = requests.get('http://localhost:3000/albums')
# Check if the status code on the response object matches a successful response
if(response.____ == ____):
print("Success!")
# Check if the status code indicates a failed authentication attempt
elif(response.____ == ____):
print('Authentication failed')
else:
print('Another error occurred')