欢迎访问宙启技术站
智能推送

使用Python编写的all_requests()函数,实现多种请求的统一处理

发布时间:2023-12-26 12:33:58

下面是一个使用Python编写的all_requests()函数的实现,该函数可以统一处理多种请求,并返回相应的结果。

import requests

def all_requests(url, params=None, headers=None, data=None, json=None, method="GET"):
    # 发送请求
    if method == "GET":
        response = requests.get(url, params=params, headers=headers)
    elif method == "POST":
        response = requests.post(url, headers=headers, data=data, json=json)
    elif method == "PUT":
        response = requests.put(url, headers=headers, data=data, json=json)
    elif method == "DELETE":
        response = requests.delete(url, headers=headers)
    else:
        raise ValueError("Unsupported HTTP method: {}".format(method))

    # 返回结果
    status_code = response.status_code
    content_type = response.headers.get("content-type")
    if "json" in content_type:
        result = response.json()
    elif "text" in content_type:
        result = response.text
    else:
        result = response.content

    return status_code, result

这个函数接受以下参数:

- url:请求的URL。

- params:GET请求的查询参数。

- headers:请求的头部。

- data:POST或PUT请求的表单数据。

- json:POST或PUT请求的JSON数据。

- method:HTTP方法,默认为GET。

该函数会根据指定的HTTP方法发送请求,并返回响应的状态码和结果。如果结果是JSON格式,会被解析为Python对象。如果结果是文本格式,则直接返回文本。如果不是以上两种格式,则返回原始内容。

下面是一个使用例子:

# 发送GET请求
status_code, result = all_requests("https://api.example.com/data", params={"id": 1})

# 发送POST请求
status_code, result = all_requests("https://api.example.com/data", method="POST", data={"name": "John", "age": 30})

# 发送PUT请求
status_code, result = all_requests("https://api.example.com/data/1", method="PUT", json={"name": "John"})

# 发送DELETE请求
status_code, result = all_requests("https://api.example.com/data/1", method="DELETE")

这些例子展示了如何使用all_requests()函数发送不同类型的请求。你可以根据你的需求自定义参数,并根据相应的请求方法调用该函数。