You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中通过字符串形式的请求发起Web服务调用?

实现通用Web服务调用函数

要实现通过字符串指定请求方法的通用调用函数,核心是利用Python的getattr()函数从requests模块中获取对应方法的函数对象。以下是完整实现:

通用函数代码

import requests
import logging

logger = logging.getLogger(__name__)

def generic_call(method: str, url: str, auth=None, params=None, data=None, verify=False):
    try:
        # 通过字符串获取对应的requests方法(如get/post)
        request_func = getattr(requests, method.lower())
        # 执行请求
        response = request_func(
            url=url,
            auth=auth,
            params=params,
            data=data,
            verify=verify
        )
        # 主动触发HTTP错误(比如4xx/5xx状态码)
        response.raise_for_status()
        # 返回JSON响应
        return response.json()
    except requests.exceptions.HTTPError as http_error:
        logger.error(f"Bad Status Code: {http_error.response.status_code}", exc_info=http_error)
        raise
    except (requests.exceptions.ConnectionError, requests.exceptions.ConnectTimeout) as connection_error:
        logger.error("Connection Problem occurred", exc_info=connection_error)
        raise
    except requests.exceptions.Timeout as timeout_error:
        logger.error("Time Out Exception occurred", exc_info=timeout_error)
        raise
    except requests.exceptions.RequestException as error:
        logger.error("Request Error occurred", exc_info=error)
        raise

使用示例

# 准备请求参数
auth = ("username", "password")
search_params = {"key": "value"}

# 发起GET请求
get_response = generic_call("get", "https://api.example.com/data", auth=auth, params=search_params)

# 发起POST请求
post_data = {"field": "content"}
post_response = generic_call("post", "https://api.example.com/submit", auth=auth, data=post_data)

关键说明

  • getattr(requests, method.lower()): 将传入的方法字符串(如"GET"或"get")转换为requests.get这样的函数对象,.lower()确保大小写不敏感。
  • 参数扩展性: 函数中包含了params、data等常见参数,你可以根据需求添加更多(如headers、json等)。
  • 错误处理: 保留了你原有的异常捕获逻辑,并添加了raise_for_status()来主动触发HTTP错误(否则requests默认不会抛出4xx/5xx的异常)。
  • 日志优化: 使用exc_info=http_error可以记录完整的异常堆栈信息,便于调试。

内容的提问来源于stack exchange,提问作者Thomas Campos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 06:32:21