Python玩转HTTP请求

云计算分享者 2024-02-22 08:18:23
背景

在互联网时代,掌握与API交互的能力至关重要。Python作为一门通用编程语言,凭借其简洁易用、功能强大的特点,成为开发人员与API交互的首选工具之一。本文介绍在Python中使用第三方库requests发送HTTP请求,学习如何获取数据、处理错误、设置超时、发送JSON数据、处理编码、使用会话、重定向以及流式传输大型响应等实用技巧,实现和其他API轻松对接!

引入 requests 包

requests 是一个 Python 第三方库,专门用于发送 HTTP 请求和处理响应。它提供了简单易用的 API,可以让我们轻松地与各种 API 进行交互。与 Python 标准库中的 urllib 模块相比,requests 具有以下优势:语法更加简洁易懂,功能更加丰富强大,支持更多高级特性。

为了使用requests包,需要在使用pip install requests进行安装。

然后在要使用requests的模块中使用import进行导入

import requests1. 基本 GET 请求

使用GET请求获取API数据,就像在浏览器中输入网址一样简单。只需一行代码,就能将服务器端的数据加载到你的程序中

import requestsresponse = requests.get('https://api.example.com/data')data = response.json() # Assuming the response is JSONprint(data)2. 带有查询参数的 GET 请求

GET请求支持参数化查询,让你可以精细地筛选目标数据。通过params参数,就能将键值对形式的参数传递给API

import requestsparams = {'key1': 'value1', 'key2': 'value2'}response = requests.get('https://api.example.com/search', params=params)data = response.json()print(data)3. 处理 HTTP 错误

网络请求难免遇到各种状况。使用raise_for_status()方法,可以捕捉4xx、5xx等错误,并进行相应的处理

import requestsresponse = requests.get('https://api.example.com/data')try: response.raise_for_status() # Raises an HTTPError if the status is 4xx, 5xx data = response.json() print(data)except requests.exceptions.HTTPError as err: print(f'HTTP Error: {err}')4. 设置请求超时

为请求设置超时时间,可以避免程序因网络延迟而无限等待。timeout参数可以指定超时秒数

import requeststry: response = requests.get('https://api.example.com/data', timeout=5) # Timeout in seconds data = response.json() print(data)except requests.exceptions.Timeout: print('The request timed out')5. 在请求中使用标头

在请求头中添加授权信息等自定义参数,可以满足特定API的需求。headers参数让你轻松实现这一功能

import requestsheaders = {'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}response = requests.get('https://api.example.com/protected', headers=headers)data = response.json()print(data)6. 带有 JSON 有效负载的 POST 请求

使用POST请求可以向API发送数据。通过json参数,可以轻松将字典格式的数据转换为JSON格式并发送

import requestspayload = {'key1': 'value1', 'key2': 'value2'}headers = {'Content-Type': 'application/json'}response = requests.post('https://api.example.com/submit', json=payload, headers=headers)print(response.json())7. 解码响应内容

要正确处理响应编码,请执行以下操作:

import requestsresponse = requests.get('https://api.example.com/data')response.encoding = 'utf-8' # Set encoding to match the expected response formatdata = response.textprint(data)8. 会话管理

使用会话对象可以管理多个请求,并保持相同的身份验证和连接信息,提升效率

import requestswith requests.Session() as session: session.headers.update({'Authorization': 'Bearer YOUR_ACCESS_TOKEN'}) response = session.get('https://api.example.com/data') print(response.json())9. 重定向处理

默认情况下,requests会自动处理重定向。设置allow_redirects参数为False,可以关闭重定向功能

import requestsresponse = requests.get('https://api.example.com/data', allow_redirects=False)print(response.status_code)10. 流式传输大响应文件

要流式传输大型响应以分块处理它,而不是将其全部加载到内存中:

import requestsresponse = requests.get('https://api.example.com/large-data', stream=True)for chunk in response.iter_content(chunk_size=1024): process(chunk) # Replace 'process' with your actual processing function

掌握以上技巧,你就能在Python的世界里自由地与API交互,获取各种数据,完成各种任务,解锁更多精彩玩法!

0 阅读:127

云计算分享者

简介:感谢大家的关注