Python编程之Requesrsmo模块带参数的 GET 请求细讲

带参数的 GET 请求是 Web 开发和 API 设计中极其常见且重要的概念。简单来说,带参数的 GET 请求主要用于向服务器传递查询条件、过滤选项或配置信息,从而获取特定的、定制化的数据,而不是全部数据。

让我通过几个关键点和实际案例来详细解释。

Requesrsmo模块带参数的 GET 请求核心原因与目的

1. 精确查询与数据过滤

这是最核心的用途。当数据量很大时,客户端通常不需要所有数据,而是需要符合特定条件的子集。

import requests

# 案例:查询特定用户的信息
# 不使用参数 - 获取所有用户,然后在客户端过滤(低效)
response = requests.get('https://api.example.com/users')  # 获取所有用户
all_users = response.json()  # 解析响应数据
# 需要在代码中遍历查找特定用户(效率低下,尤其当用户数量很大时)

# 使用参数 - 让服务器直接返回所需数据(高效)
params = {'username': 'alice'}  # 定义查询参数:用户名为alice
response = requests.get('https://api.example.com/users', params=params)  # 发送带参数的GET请求
user_data = response.json()  # 直接得到用户alice的数据
print(f"请求的URL: {response.url}")  # 查看实际请求的URL(包含参数)
# 实际URL可能是: https://api.example.com/users?username=alice

2. 分页显示大量数据

当数据量很大时,一次性获取所有数据既不现实也不高效,分页是解决方案。

import requests

# 案例:获取论坛帖子分页数据
page = 2        # 请求第2页
limit = 20      # 每页20条

params = {
    'page': page,    # 页码参数
    'limit': limit   # 每页数量参数
}

# 获取第2页的帖子,每页20条
response = requests.get('https://api.example.com/posts', params=params)
posts_page_2 = response.json()  # 直接得到第2页的数据

print(f"实际请求URL: {response.url}")
# 可能是: https://api.example.com/posts?page=2&limit=20

3. 排序和筛选

让服务器按照特定方式处理和返回数据。

import requests

# 案例:获取商品列表,按价格降序排列
params = {
    'category': 'electronics',  # 筛选类别:电子产品
    'sort': 'price',           # 按价格排序
    'order': 'desc'            # 降序排列
}

response = requests.get('https://api.example.com/products', params=params)
sorted_products = response.json()

print(f"请求URL: {response.url}")
# 可能是: https://api.example.com/products?category=electronics&sort=price&order=desc

4. 搜索功能

实现关键字搜索和复杂查询。

import requests

# 案例:搜索包含特定关键词的文章
params = {
    'q': 'python web development',  # 搜索关键词
    'type': 'article',              # 内容类型:文章
    'year': '2023'                  # 年份限制:2023年
}

response = requests.get('https://api.example.com/search', params=params)
search_results = response.json()

print(f"搜索请求URL: {response.url}")
# 可能是: https://api.example.com/search?q=python+web+development&type=article&year=2023

5. API 密钥和身份验证

一些API需要密钥或其他认证参数。

import requests
import os

# 从环境变量获取API密钥(安全做法)
API_KEY = os.getenv('MY_API_KEY')  # 获取环境变量中的API密钥

params = {
    'api_key': API_KEY,  # API密钥参数
    'format': 'json'     # 响应格式:JSON
}

response = requests.get('https://api.someervice.com/data', params=params)
data = response.json()

工作原理:URL 查询字符串

当使用 requests.get(params=...) 时,requests 库会自动将这些参数转换为 URL 的查询字符串(Query String)

https://api.example.com/endpoint?key1=value1&key2=value2&key3=value3
  • ? 标记查询字符串的开始
  • key=value 形式表示参数名和值
  • & 用于分隔多个参数

实际应用场景

场景1:天气预报API

import requests

def get_weather(city, units='metric'):
    """
    获取指定城市的天气预报
    
    Args:
        city (str): 城市名称
        units (str): 温度单位,metric(摄氏度)或imperial(华氏度)
    """
    # API参数配置
    params = {
        'q': city,           # 城市名称
        'units': units,      # 温度单位
        'appid': 'your_api_key_here'  # API密钥(实际使用时需要替换)
    }
    
    try:
        # 发送带参数的GET请求
        response = requests.get('https://api.openweathermap.org/data/2.5/weather', 
                               params=params, 
                               timeout=10)
        
        response.raise_for_status()  # 检查HTTP错误
        
        data = response.json()
        print(f"{city}的天气: {data['weather'][0]['description']}")
        print(f"温度: {data['main']['temp']}°{'C' if units == 'metric' else 'F'}")
        print(f"请求URL: {response.url}")
        
    except requests.exceptions.RequestException as e:
        print(f"获取天气信息失败: {e}")

# 使用示例
get_weather('Beijing')      # 获取北京天气(摄氏度)
get_weather('New York', 'imperial')  # 获取纽约天气(华氏度)

场景2:电商网站商品筛选

import requests

def search_products(keyword=None, category=None, min_price=None, max_price=None, sort_by='price'):
    """
    搜索商品
    
    Args:
        keyword (str): 搜索关键词
        category (str): 商品类别
        min_price (float): 最低价格
        max_price (float): 最高价格
        sort_by (str): 排序方式
    """
    params = {}  # 初始化空参数字典
    
    # 根据需要添加参数
    if keyword:
        params['q'] = keyword
    if category:
        params['category'] = category
    if min_price is not None:
        params['min_price'] = min_price
    if max_price is not None:
        params['max_price'] = max_price
    if sort_by:
        params['sort_by'] = sort_by
    
    try:
        response = requests.get('https://api.ecommerce.com/products', 
                               params=params,
                               timeout=8)
        
        response.raise_for_status()
        
        products = response.json()
        print(f"找到 {len(products)} 个商品")
        print(f"请求URL: {response.url}")
        
        return products
        
    except requests.exceptions.RequestException as e:
        print(f"搜索商品失败: {e}")
        return []

# 使用示例
# 搜索价格在100-500元之间的电子产品
products = search_products(
    keyword='laptop',       # 关键词:笔记本
    category='electronics', # 类别:电子产品
    min_price=100,          # 最低价格:100元
    max_price=500,          # 最高价格:500元
    sort_by='price'         # 按价格排序
)

重要注意事项

  1. 参数安全性:GET 参数在 URL 中可见,不要用于传输敏感信息(密码、令牌等)
  2. URL 长度限制:浏览器和服务器对 URL 长度有限制(通常 2048 字符左右)
  3. 参数编码:requests 库会自动处理特殊字符的编码
  4. 幂等性:GET 请求应该是幂等的(多次执行相同效果)
# 错误示范:用GET请求发送敏感信息
params = {
    'username': 'alice',
    'password': 'secret123'  # 密码明文暴露在URL中!
}
# 应该使用POST请求和请求体来传输敏感信息

# 正确做法:使用POST请求发送敏感信息
data = {
    'username': 'alice',
    'password': 'secret123'
}
response = requests.post('https://api.example.com/login', data=data)

总结

带参数的 GET 请求之所以存在且被广泛使用,主要是因为它们:

  1. 提高效率:让服务器进行数据过滤,减少不必要的数据传输
  2. 增强灵活性:客户端可以定制需要获取的数据
  3. 支持复杂查询:实现搜索、排序、分页等高级功能
  4. 符合 RESTful 原则:GET 请求用于获取数据,参数用于指定获取什么数据
  5. 可缓存和共享:参数化的 URL 可以被缓存、书签保存和分享

理解和使用带参数的 GET 请求是 Web 开发和 API 使用的核心技能之一,能够大大提高程序的效率和灵活性。

Logo

葡萄城是专业的软件开发技术和低代码平台提供商,聚焦软件开发技术,以“赋能开发者”为使命,致力于通过表格控件、低代码和BI等各类软件开发工具和服务

更多推荐